Skip to content

Commit 6c67711

Browse files
akaashhazarikaBenRKarl
authored andcommitted
Add Adwords -> Google Ads Migration Examples (#149)
1 parent 6b35e6f commit 6c67711

8 files changed

Lines changed: 1964 additions & 0 deletions

examples/migration/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Google Ads Client Library for Python - Migration examples
2+
3+
This folder contains code examples that illustrate how to migrate from the
4+
AdWords API to the Google Ads API in a step-by-step manner. The following code
5+
examples are provided.
6+
7+
8+
CampaignManagement
9+
This folder contains a code example that shows how to create a Google Ads Search
10+
campaign. The code example does the following operations:
11+
12+
* Create a budget
13+
* Create a campaign
14+
* Create an ad group
15+
* Create text ads
16+
* Create keywords
17+
18+
19+
The code example starts with create_complete_campaign_adwords_api_only.py that
20+
shows the whole functionality developed in AdWords API.
21+
create_complete_campaign_both_apis_phase_1.py through
22+
create_complete_campaign_both_apis_phase_4.py shows how to migrate functionality
23+
incrementally from the AdWords API to the Google Ads API.
24+
create_complete_campaign_google_ads_api_pnly.py shows the code example fully
25+
transformed into using the Google Ads API.
26+
27+
Running the examples:
28+
1. cd into ./migration directory.
29+
2. Run pip install -r requirements.txt to install dependencies.
30+
3. Fill in the required authentication credentials, see
31+
[here](https://github.com/googleads/google-ads-python#configuration-file-setup)
32+
for the Google Ads API client library, and
33+
[here](https://github.com/googleads/googleads-python-lib#getting-started) for
34+
the AdWords client library.
35+
4. Run each example from the command line, providing the required parameters.
36+
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Copyright 2019 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# https://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
"""This example creates a search campaign with the help of AdWords Api.
17+
18+
This code example is the first in a series of code examples that shows how to
19+
create a Search campaign using the AdWords API, and then migrate it to Google
20+
Ads API one functionality at a time. See other examples in this directory for
21+
code examples in various stages of migration.
22+
23+
This code example represents the initial state, where the AdWords API is used
24+
to create a campaign budget, a Search campaign, ad groups, keywords and expanded
25+
text ads. None of the functionality has yet been migrated to the Google Ads API.
26+
"""
27+
28+
29+
import datetime
30+
import urllib.parse
31+
import uuid
32+
33+
from googleads import adwords
34+
35+
# Number of ads being added/updated in this code example.
36+
NUMBER_OF_ADS = 5
37+
# The list of keywords being added in this code example.
38+
KEYWORDS_TO_ADD = ['mars cruise', 'space hotel']
39+
40+
41+
def create_campaign_budget(client):
42+
"""Creates a new budget and returns the newly created budget ID.
43+
44+
Args:
45+
client: An instance of the google.ads.google_ads.client.GoogleAdsClient
46+
class.
47+
48+
Returns:
49+
(str) Budget ID of the newly created budget.
50+
"""
51+
budget_service = client.GetService('BudgetService', version='v201809')
52+
budget = {
53+
'name' : 'Interplanetary Cruise Budget #{}'.format(uuid.uuid4()),
54+
'amount': {
55+
'microAmount' : '50000000'
56+
},
57+
'deliveryMethod' : 'STANDARD'
58+
}
59+
budget_operations = [{
60+
'operator': 'ADD',
61+
'operand': budget
62+
}]
63+
# Add budget.
64+
results = budget_service.mutate(budget_operations)
65+
created_budget = results['value'][0]
66+
print('Budget with ID {} and name {} was created'.format(
67+
created_budget['budgetId'], created_budget['name']))
68+
return created_budget['budgetId']
69+
70+
71+
def create_campaign(client, budget_id):
72+
"""Creates a new campaign and returns the newly created campaign ID.
73+
74+
Args:
75+
client: A google.ads.google_ads.client.GoogleAdsClient instance.
76+
budget_id: (str) Budget ID to be referenced while creating Campaign.
77+
78+
Returns:
79+
(str) Campaign ID of the newly created Campaign.
80+
"""
81+
campaign_service = client.GetService('CampaignService', version='v201809')
82+
campaign = {
83+
'name': 'Interplanetary Cruise #{}'.format(uuid.uuid4()),
84+
'advertisingChannelType': 'SEARCH',
85+
# Recommendation: Set the campaign to PAUSED when creating it to stop the
86+
# ads from immediately serving. Set to ENABLED once you've added
87+
# targeting and the ads are ready to serve.
88+
'status': 'PAUSED',
89+
'biddingStrategyConfiguration': {
90+
'biddingStrategyType': 'MANUAL_CPC',
91+
},
92+
'startDate': (datetime.datetime.now() +
93+
datetime.timedelta(1)).strftime('%Y%m%d'),
94+
'endDate': (datetime.datetime.now() +
95+
datetime.timedelta(365)).strftime('%Y%m%d'),
96+
# Budget (required) - note only the budget ID is required.
97+
'budget': {
98+
'budgetId': budget_id
99+
},
100+
'networkSetting': {
101+
'targetGoogleSearch': 'true',
102+
'targetSearchNetwork': 'true',
103+
}
104+
}
105+
campaign_operations = [{
106+
'operator': 'ADD',
107+
'operand': campaign
108+
}]
109+
results = campaign_service.mutate(campaign_operations)
110+
created_campaign = results['value'][0]
111+
print('CreatedCampign with ID {} and name {} was created'.format(
112+
created_campaign['id'], created_campaign['name']))
113+
return created_campaign['id']
114+
115+
116+
def create_ad_group(client, campaign_id):
117+
"""Creates a new ad group and returns the new created ad group ID.
118+
119+
Args:
120+
client: A google.ads.google_ads.client.GoogleAdsClient instance.
121+
campaign_id: (str) The ID of the campaign under which to create a new
122+
ad group.
123+
124+
Returns:
125+
(str) Ad group ID of the newly created ad group.
126+
"""
127+
ad_group_service = client.GetService('AdGroupService', 'v201809')
128+
ad_group = {
129+
'name': 'Earth to Mars Cruise #{}'.format(uuid.uuid4()),
130+
'campaignId': campaign_id,
131+
'status': 'ENABLED',
132+
'biddingStrategyConfiguration' : {
133+
'bids': [{
134+
# The 'xsi_type' field allows you to specify the xsi:type of the
135+
# object being created. It's only necessary when you must provide
136+
# an explicit type that the client library can't infer.
137+
'xsi_type': 'CpcBid',
138+
'bid': {
139+
'microAmount': 10000000
140+
}
141+
}]
142+
},
143+
'adGroupAdRotationMode': 'OPTIMIZE'
144+
}
145+
146+
adgroup_operations = [{
147+
'operator': 'ADD',
148+
'operand': ad_group
149+
}]
150+
results = ad_group_service.mutate(adgroup_operations)
151+
created_ad_group = results['value'][0]
152+
print('Ad group with ID {} and name {} was created'.format(
153+
created_ad_group['id'], created_ad_group['name']))
154+
return created_ad_group['id']
155+
156+
157+
def create_text_ads(client, ad_group_id):
158+
"""Creates text ads using the given ad group ID.
159+
160+
Args:
161+
client: A google.ads.google_ads.client.GoogleAdsClient instance.
162+
ad_group_id: (str) Ad group ID to be referenced when creating text ads.
163+
"""
164+
ad_group_service = client.GetService('AdGroupAdService', 'v201809')
165+
operations = []
166+
for i in range(NUMBER_OF_ADS):
167+
operation = {
168+
'xsi_type': 'AdGroupAd',
169+
'adGroupId': ad_group_id,
170+
# Additional properties (non-required).
171+
'status': 'PAUSED',
172+
'ad': {
173+
'xsi_type': 'ExpandedTextAd',
174+
'headlinePart1': 'Cruise #{} to Mars'.format(
175+
str(uuid.uuid4())[:8]),
176+
'headlinePart2': 'Best Space Cruise Line',
177+
'headlinePart3': 'For Your Loved Ones',
178+
'description': 'Buy your tickets now!',
179+
'description2': 'Discount ends soon',
180+
'finalUrls': ['http://www.example.com/']
181+
}
182+
}
183+
adgroup_operations = {
184+
'operator': 'ADD',
185+
'operand': operation
186+
}
187+
operations.append(adgroup_operations)
188+
189+
results = ad_group_service.mutate(operations)
190+
for result in results['value']:
191+
print('Expanded text ad with ID {} and '
192+
'headline {}-{} {} was created'.format(
193+
result['ad']['id'], result['ad']['headlinePart1'],
194+
result['ad']['headlinePart2'], result['ad']['headlinePart3']))
195+
196+
197+
def create_keywords(client, ad_group_id, keywords_to_add):
198+
"""Populates keywords on a given ad group ID.
199+
200+
Args:
201+
client: A google.ads.google_ads.client.GoogleAdsClient instance.
202+
ad_group_id: (str) Ad group ID to be referenced when creating text ads.
203+
keywords_to_add: (list) A list of keywords to be added to a given ad
204+
group.
205+
"""
206+
ad_group_criterion_service = client.GetService('AdGroupCriterionService',
207+
'v201809')
208+
operations = []
209+
for keyword in keywords_to_add:
210+
operation = {
211+
'xsi_type': 'BiddableAdGroupCriterion',
212+
'adGroupId': ad_group_id,
213+
'criterion': {
214+
'xsi_type' : 'Keyword',
215+
'text': keyword,
216+
'matchType' : 'BROAD'
217+
},
218+
'userStatus': 'PAUSED',
219+
'finalUrls' : ['http://www.example.com/mars/cruise/?kw={}'.format(
220+
urllib.parse.quote(keyword))]
221+
}
222+
create_keyword = {
223+
'operator': 'ADD',
224+
'operand': operation
225+
}
226+
operations.append(create_keyword)
227+
228+
results = ad_group_criterion_service.mutate(operations)
229+
for result in results['value']:
230+
print('Keyword with ad group ID {}, keyword ID {}, text {} and match'
231+
'type {} was created'.format(result['adGroupId'],
232+
result['criterion']['id'], result['criterion']['text'],
233+
result['criterion']['matchType']))
234+
235+
236+
if __name__ == '__main__':
237+
# Initialize the client object.
238+
# By default, it will read the config file from the Home Directory.
239+
adwords_client = adwords.AdWordsClient.LoadFromStorage()
240+
budget_id = create_campaign_budget(adwords_client)
241+
campaign_id = create_campaign(adwords_client, budget_id)
242+
ad_group_id = create_ad_group(adwords_client, campaign_id)
243+
create_text_ads(adwords_client, ad_group_id)
244+
create_keywords(adwords_client, ad_group_id, KEYWORDS_TO_ADD)

0 commit comments

Comments
 (0)