def testWithCachedRefreshToken(self): """Tests the entire workflow of making a request against AdWords. Uses a cached refresh token to generate a credential. Since this library is tightly integrated with SOAPpy, this test mocks out the HTTP level rather than the SOAPpy proxy level. """ directory = self._CreateConfigPickles() try: with mock.patch( 'oauth2client.client.OAuth2Credentials.refresh') as mock_refresh: client = AdWordsClient(path=directory) self.assertEquals(CLIENT_ID, client.oauth2credentials.client_id) self.assertEquals(CLIENT_SECRET, client.oauth2credentials.client_secret) self.assertEquals(REFRESH_TOKEN, client.oauth2credentials.refresh_token) def SetAccessToken(unused_http): client.oauth2credentials.access_token = ACCESS_TOKEN mock_refresh.side_effect = SetAccessToken campaign_service = self._CreateCampaignService(client) page = self._MakeSoapRequest(campaign_service) # Assert that the serialized objects returned in the SOAP response # deserialize to the expected output. Also check that we correctly # interpret the operations. self.assertEquals(EXPECTED_PAGE, page) self.assertEquals(8, client.GetOperations()) client.oauth2credentials.refresh.assert_called_once_with(mock.ANY) finally: shutil.rmtree(directory)
def setUp(self): """Prepare unittest.""" self.client = AdWordsClient(headers={ 'authToken': ' ', 'userAgent': ' ', 'developerToken': ' ' })
def setUp(self): """Prepare unittest.""" self.client = AdWordsClient( headers={ 'oauth2credentials': 'credential!', 'userAgent': 'USER AGENT', 'developerToken': 'DEV TOKEN' })
def setUp(self): """Prepare unittest.""" self.client = AdWordsClient( headers={ 'authToken': 'AUTH TOKEN', 'userAgent': 'USER AGENT', 'developerToken': 'DEV TOKEN' })
def testIntegerClientCustomerId(self): """Tests if we can convert an integer clientCustomerId to string.""" client = AdWordsClient({ 'authToken': 'abc', 'developerToken': 'abc', 'userAgent': 'foo', 'clientCustomerId': 123 }) campaign_service = client.GetCampaignService() campaign_service._SetHeaders()
def __init__(self, client_id, client_secret, refresh_token, mcc_cid, dev_token, debug=False): """Initializes an APIHandler. Args: client_id: client_secret: refresh_token: mcc_cid: dev_token: debug: """ credentials = OAuth2Credentials(None, client_id, client_secret, refresh_token, None, self._REFRESH_URL, self._USER_AGENT) credentials.refresh(httplib2.Http()) headers = { 'clientCustomerId': mcc_cid, 'userAgent': self._USER_AGENT, 'developerToken': dev_token, 'validateOnly': 'n', 'partialFailure': 'n', 'oauth2credentials': credentials } # App Engine doesn't allow you to write to the disk. Thus, we need to # explicitly turn off logging. Though, if debugging is enabled, the # data from STDOUT will be redirected to app engine's debugging console. # Note that we also specify that we want to use ElementTree here; see the # README for more information if you would rather use PyXML. config = { 'debug': Utils.BoolTypeConvert(debug), 'xml_log': 'n', 'request_log': 'n', 'pretty_xml': 'n', 'xml_parser': '2', # We're using ElementTree. 'compress': 'n' } self.client = AdWordsClient(headers, config) self.client.use_mcc = True
def testAuthTokenOthersBlank(self): """Tests that authToken with other auth blank works.""" headers = DEFAULT_HEADERS.copy() headers['authToken'] = 'MyToken' headers['email'] = '' headers['password'] = '' headers['oauth_credentials'] = None client = AdWordsClient(headers=headers) self.assertEquals(client._headers['authToken'], 'MyToken')
def testOAuthCredentialsOthersBlank(self): """Tests that oauth_credentials with other auth blank works.""" headers = DEFAULT_HEADERS.copy() headers['oauth2credentials'] = 'credential!' headers['email'] = '' headers['password'] = '' headers['authToken'] = '' client = AdWordsClient(headers=headers) self.assertTrue(client.oauth2credentials)
def testDownloadReportWithRequestLogDisabled(self): """Tests if we can download a report with request logging disabled.""" client = AdWordsClient(path=os.path.join('..', '..', '..')) client._config['request_log'] = 'n' # pylint: disable=W0212 report_downloader = client.GetReportDownloader() report = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', 'reportType': 'CRITERIA_PERFORMANCE_REPORT', 'downloadFormat': 'CSV', 'selector': { 'fields': ['CampaignId', 'AdGroupId', 'Id', 'CriteriaType', 'Criteria', 'Impressions', 'Clicks', 'Cost'] }, # Enable to get rows with zero impressions. 'includeZeroImpressions': 'false' } report_downloader.DownloadReport(report)
def assertSetter(self, value, expected): """Constructs an AdWordsClient and sets value using setters.. Tests that the provided value is parsed to the expected value in the setter methods method. Args: value: multiple Value to test. expected: multiple Expected value. """ client = AdWordsClient(headers={ 'authToken': '...', 'clientCustomerId': '1234567890', 'userAgent': 'GoogleTest', 'developerToken': '[email protected]++USD' }) client.partial_failure = value client.validate_only = value self.assertEquals(client.partial_failure, expected)
def testCaptchaHandling(self): headers = DEFAULT_HEADERS.copy() headers['email'] = '*****@*****.**' headers['password'] = '******' client = None try: with mock.patch('urllib2.urlopen') as mock_urlopen: mock_urlopen.return_value = StringIO.StringIO( self.CAPTCHA_CHALLENGE) client = AdWordsClient(headers=headers) self.fail('Expected a CaptchaError to be thrown') except ValidationError, e: with mock.patch('urllib2.urlopen') as mock_urlopen: mock_urlopen.return_value = StringIO.StringIO(self.SUCCESS) client = AdWordsClient(headers=headers, login_token=e.root_cause.captcha_token, login_captcha='foo bar') self.assertEquals(client._headers['authToken'], 'DQAAAGgA...dk3fA5N')
def assertSetter(self, value, expected): """Constructs an AdWordsClient and sets value using setters.. Tests that the provided value is parsed to the expected value in the setter methods method. Args: value: multiple Value to test. expected: multiple Expected value. """ client = AdWordsClient( headers={ 'authToken': '...', 'clientCustomerId': '1234567890', 'userAgent': 'GoogleTest', 'developerToken': '[email protected]++USD' }) client.partial_failure = value client.validate_only = value self.assertEquals(client.partial_failure, expected)
def testRegenerateTokenInReportDownload(self): """Tests if the report download token regeneration logic works..""" client = AdWordsClient(path=os.path.join('..', '..', '..')) report_downloader = client.GetReportDownloader() report_downloader._config['auth_token_epoch'] = 0 report = { 'reportName': 'Last 7 days CRITERIA_PERFORMANCE_REPORT', 'dateRangeType': 'LAST_7_DAYS', 'reportType': 'CRITERIA_PERFORMANCE_REPORT', 'downloadFormat': 'CSV', 'selector': { 'fields': [ 'CampaignId', 'AdGroupId', 'Id', 'CriteriaType', 'Criteria', 'Impressions', 'Clicks', 'Cost' ] }, # Enable to get rows with zero impressions. 'includeZeroImpressions': 'false' } report_downloader.DownloadReport(report)
def get_ads_cost(date_min, date_max, client=None): if not client: client = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..')) ad_group_service = client.GetAdGroupService(version='v201306') cost = 0 offset = 0 selector = { 'fields': ['Id', 'Cost'], 'paging': { 'startIndex': str(offset), 'numberResults': str(PAGE_SIZE) }, 'predicates': [{ 'field': 'CampaignName', 'operator': 'STARTS_WITH', 'values': ['PLA - '] }], 'dateRange': { 'min': date_min, 'max': date_max } } more_pages = True while more_pages: page = ad_group_service.Get(selector)[0] # Display results. if 'entries' in page: for entry in page['entries']: cost += int(entry['stats']['cost']['microAmount']) else: print 'No ad group was found.' offset += PAGE_SIZE selector['paging']['startIndex'] = str(offset) more_pages = offset < int(page['totalNumEntries']) time.sleep(1) print 'AdGroupService %s...' % offset return cost
def testEmailPassOnly(self): """Tests that specifying solely email & password works.""" with mock.patch( 'adspygoogle.common.Utils.GetAuthToken') as mock_get_token: mock_get_token.return_value = 'FooBar' headers = DEFAULT_HEADERS.copy() headers['email'] = '*****@*****.**' headers['password'] = '******' client = AdWordsClient(headers=headers) self.assertEquals(client._headers['authToken'], 'FooBar') mock_get_token.assert_called_once_with('*****@*****.**', 'password', mock.ANY, mock.ANY, mock.ANY, mock.ANY, mock.ANY)
def testRequestWithOAuth2FromFile(self): """Tests making a request against AdWords using cached OAuth2 values.""" path = tempfile.mkdtemp() auth_credentials = { 'clientCustomerId': CLIENT_CUSTOMER_ID, 'developerToken': DEVELOPER_TOKEN, 'userAgent': USER_AGENT, 'clientId': CLIENT_ID, 'clientSecret': CLIENT_SECRET, 'refreshToken': REFRESH_TOKEN } with open(os.path.join(path, 'adwords_api_auth.pkl'), 'w') as handle: pickle.dump(auth_credentials, handle) handle.close() with open(os.path.join(path, 'adwords_api_config.pkl'), 'w') as handle: pickle.dump({}, handle) handle.close() budget = { 'name': 'Interplanetary budget #%s' % Utils.GetUniqueName(), 'amount': { 'microAmount': '50000000' }, 'deliveryMethod': 'STANDARD', 'period': 'DAILY' } budget_operations = [{'operator': 'ADD', 'operand': budget}] client = AdWordsClient(path=path) budget_service = client.GetBudgetService() response = budget_service.Mutate(budget_operations)[0] self.assertEqual('BudgetReturnValue', response.get('ListReturnValue_Type')) self.assertEqual(1, len(response.get('value', [])))
def testEmailPassOthersBlank(self): """Tests that email and password with other auth blank works.""" with mock.patch( 'adspygoogle.common.Utils.GetAuthToken') as mock_get_token: mock_get_token.return_value = 'FooBar' headers = DEFAULT_HEADERS.copy() headers['email'] = '*****@*****.**' headers['password'] = '******' headers['authToken'] = '' headers['oauth_credentials'] = None client = AdWordsClient(headers=headers) self.assertEquals(client._headers['authToken'], 'FooBar') mock_get_token.assert_called_once_with('*****@*****.**', 'password', mock.ANY, mock.ANY, mock.ANY, mock.ANY, mock.ANY)
def _CreateAdWordsClient(self, oauth2_credential): """Creates an AdWordsClient using the given OAuth2 credential. Args: oauth2_credential: oauth2client.client.OAuth2Credentials The credential object this client will use to authenticate. Returns: adspygoogle.adwords.AdWordsClient.AdwordsClient A client ready to make requests against the AdWords API. """ headers = { 'userAgent': USER_AGENT, 'developerToken': DEVELOPER_TOKEN, 'clientCustomerId': CLIENT_CUSTOMER_ID, 'oauth2credentials': oauth2_credential } return AdWordsClient(headers=headers)
def assertDefaultConstructor(self, value, expected): """Constructs an AdWordsClient using value in headers. Tests that the provided value is parsed to the expected value in the __init__ method. Args: value: multiple Value to test. expected: multiple Expected value. """ client = AdWordsClient( headers={ 'authToken': '...', 'clientCustomerId': '1234567890', 'userAgent': 'GoogleTest', 'developerToken': '[email protected]++USD', 'validateOnly': value, 'partialFailure': value }) self.assertEquals(client.partial_failure, expected) self.assertEquals(client.validate_only, expected)
def getClient(): client = AdWordsClient( path='~/', headers={ 'clientCustomerId': '433-908-0283', #Lars MCC #'clientCustomerId': '990-671-7951', #SANDBOX ACCT #'clientCustomerId':'450-614-3003', #'clientCustomerId':'9663107432', 'developerToken': 'KuxisPFnqHFfkJetsOyMGQ', 'email': '*****@*****.**', 'password': '******', 'userAgent': 'Lars', 'debug': 'y', 'home': '/home/ubuntu', 'log_home': '/home/ubuntu/logs', 'request_log': 'y', 'xml_log': 'y', 'xml_parser': '1' }) return client
class AdWordsErrorsTestV13(unittest.TestCase): """Unittest suite for AdWordsErrors using v13.""" SERVER = SERVER_V13 VERSION = VERSION_V13 TRIGGER_MSG1 = 'The developer token is invalid.' TRIGGER_CODE1 = 42 TRIGGER_MSG2 = 'Login with this username/password failed.' TRIGGER_CODE2 = 9 dummy_client = AdWordsClient(path=os.path.join('..', '..', '..'), headers={'email': 'xxxxxx', 'password': '******', 'useragent': 'ErrorsTest', 'developerToken': 'xxxxxx++USD'}) dummy_client.debug = False dummy_client.soap_lib = client.soap_lib def setUp(self): """Prepare unittest.""" print self.id() self.__class__.dummy_client.use_mcc = True def tearDown(self): """Finalize unittest.""" self.__class__.dummy_client.use_mcc = False def testApiError(self): """Tests whether we can catch an AdWordsErrors.AdWordsApiError exception.""" try: self.__class__.dummy_client.GetAccountService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY).GetAccountInfo() except AdWordsApiError, e: try: self.assertEqual(e.message, self.__class__.TRIGGER_MSG1) self.assertEqual(e.code, self.__class__.TRIGGER_CODE1) except: self.assertEqual(e.message, self.__class__.TRIGGER_MSG2) self.assertEqual(e.code, self.__class__.TRIGGER_CODE2)
Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import datetime import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) client.use_mcc = True # Initialize appropriate service. info_service = client.GetInfoService( 'https://adwords-sandbox.google.com', 'v201008') # Construct info selector object and retrieve usage info. today = datetime.datetime.today() selector = { 'dateRange': { 'min': today.strftime('%Y%m01'), 'max': today.strftime('%Y%m%d') }, 'apiUsageType': 'OPERATION_COUNT' }
Tags: AdGroupAdService.mutate, AdParamService.mutate Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. ad_group_ad_service = client.GetAdGroupAdService( 'https://adwords-sandbox.google.com', 'v201008') ad_param_service = client.GetAdParamService( 'https://adwords-sandbox.google.com', 'v201008') ad_group_id = 'INSERT_AD_GROUP_ID_HERE' criterion_id = 'INSERT_CRITERION_ID_HERE' # Construct operations for adding text ad object and add to an ad group. operations = [{ 'operator': 'ADD', 'operand': { 'xsi_type': 'AdGroupAd',
# limitations under the License. """This example gets and downloads a report from a report definition. To get a report definition, run add_keywords_performance_report_definition.py. Currently, there is only production support for report download.""" __author__ = '[email protected] (Kevin Winter)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. report_definition_service = client.GetReportDefinitionService( 'https://adwords-sandbox.google.com', 'v201101') report_definition_id = 'INSERT_REPORT_DEFINITION_ID' file_name = 'INSERT_OUTPUT_FILE_NAME_HERE' path = os.path.join(os.path.abspath('.'), file_name) # Download report. data = report_definition_service.DownloadReport(report_definition_id) # Save report to a data file. fh = open(path, 'w')
Tags: MediaService.get """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient from adspygoogle.common import Utils # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. media_service = client.GetMediaService('https://adwords-sandbox.google.com', 'v201003') # Construct selector and get all images. selector = {'mediaType': 'IMAGE'} images = media_service.Get(selector)[0] # Display results. if 'media' in images: for image in images['media']: dimensions = Utils.GetDictFromMap(image['dimensions']) print( 'Image with id \'%s\', dimensions \'%sx%s\', and MIME type \'%s\' '
Tags: TargetingIdeaService.get Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. targeting_idea_service = client.GetTargetingIdeaService( 'https://adwords-sandbox.google.com', 'v201008') # Construct selector object and retrieve related keywords. keyword = 'space cruise' selector = { 'searchParameters': [{ 'xsi_type': 'RelatedToKeywordSearchParameter', 'keywords': [{ 'text': keyword, 'matchType': 'EXACT' }] }],
__author__ = '[email protected] (Kevin Winter)' import base64 import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient from adspygoogle.common import SOAPPY from adspygoogle.common import Utils # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. media_service = client.GetMediaService( 'https://adwords-sandbox.google.com', 'v201101') image_data = Utils.ReadFile('INSERT_IMAGE_PATH_HERE') if client.soap_lib == SOAPPY: image_data = base64.encodestring(image_data) # Construct media and upload image. media = [{ # TODO: SOAPpy needs an xsi_type here, but SOAPpy has other problems 'data': image_data, 'type': 'IMAGE' }]
Tags: CampaignService.get Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. campaign_service = client.GetCampaignService( 'https://adwords-sandbox.google.com', 'v200909') # Construct selector and get all campaigns. selector = {} campaigns = campaign_service.Get(selector)[0] # Display results. if 'entries' in campaigns: for campaign in campaigns['entries']: print( 'Campaign with id \'%s\', name \'%s\', and status \'%s\' was found.' % (campaign['id'], campaign['name'], campaign['status']))
Tags: GeoLocationService.get, CampaignAdExtensionService.mutate Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. geo_location_service = client.GetGeoLocationService( 'https://adwords-sandbox.google.com', 'v201003') campaign_ad_extension_service = client.GetCampaignAdExtensionService( 'https://adwords-sandbox.google.com', 'v201003') campaign_id = 'INSERT_CAMPAIGN_ID_HERE' # Construct selector and get geo location info for given addresses. selector = { 'addresses': [ { 'streetAddress': '1600 Amphitheatre Parkway', 'cityName': 'Mountain View',
Tags: InfoService.get Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) client.use_mcc = True # Initialize appropriate service. info_service = client.GetInfoService('https://adwords-sandbox.google.com', 'v200909') # Construct info selector object and retrieve usage info. selector = {'apiUsageType': 'TOTAL_USAGE_API_UNITS_PER_MONTH'} info = info_service.Get(selector)[0] # Display results. print('The total number of API units available this month is \'%s\'.' % info['cost']) print
"""This example gets report fields. Tags: ReportDefinitionService.getReportFields """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service. report_definition_service = client.GetReportDefinitionService( 'https://adwords-sandbox.google.com', 'v201003') report_type = 'INSERT_REPORT_TYPE_HERE' # Get report fields. fields = report_definition_service.GetReportFields(report_type) # Display results. print 'Report type \'%s\' contains the following fields:' % report_type for field in fields: print ' - %s (%s)' % (field['fieldName'], field['fieldType']) if field['enumValues']:
Api: AdWordsOnly """ __author__ = '[email protected] (Stan Grinberg)' import datetime import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) client.use_mcc = True # Initialize appropriate service. info_service = client.GetInfoService( 'https://adwords-sandbox.google.com', 'v200909') # Construct info selector object and retrieve usage info. today = datetime.datetime.today() selector = { 'dateRange': { 'min': today.strftime('%Y%m01'), 'max': today.strftime('%Y%m%d') }, 'apiUsageType': 'UNIT_COUNT' }
""" __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient from adspygoogle.adwords.AdWordsErrors import AdWordsRequestError from adspygoogle.common import Utils # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Initialize appropriate service with validate only flag enabled. client.validate_only = True campaign_service = client.GetCampaignService( 'https://adwords-sandbox.google.com', 'v201003') # Construct operations for adding campaign object and attempt to add campaign. operations = [{ 'operator': 'ADD', 'operand': { 'name': 'Campaign #%s' % Utils.GetUniqueName(), 'status': 'PAUSED', 'biddingStrategy': { 'type': 'ManualCPC' },
The Sandbox is cleared by setting status of all campaigns to "Deleted". """ __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.append(os.path.join('..', '..', '..')) from adspygoogle.adwords.AdWordsClient import AdWordsClient SERVER = 'https://adwords-sandbox.google.com' VERSION = 'v200909' client = AdWordsClient(path=os.path.join('..', '..')) client.debug = False client.use_mcc = False selector = { 'campaignStatuses': ['ACTIVE', 'PAUSED'] } campaign_service = client.GetCampaignService(SERVER, VERSION) campaigns = campaign_service.Get(selector)[0] if 'entries' in campaigns: campaigns = campaigns['entries'] operations = [] for campaign in campaigns: print '%s: status=\'%s\'' % (campaign['name'], campaign['status']),
Tags: AdGroupCriterionService.mutate """ __author__ = '[email protected] (Kevin Winter)' import os import re import sys sys.path.append(os.path.join('..', '..', '..', '..')) # Import appropriate classes from the client library. from adspygoogle.adwords.AdWordsClient import AdWordsClient # Initialize client object. client = AdWordsClient(path=os.path.join('..', '..', '..', '..')) # Enable partial failure. client.partial_failure = True # Initialize appropriate service. ad_group_criterion_service = client.GetAdGroupCriterionService( 'https://adwords-sandbox.google.com', 'v201101') ad_group_id = 'INSERT_AD_GROUP_ID_HERE' # Construct keyword ad group criteria objects. keywords = [ { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_group_id,