Skip to content

Commit 19d8ab4

Browse files
authored
Added annotations to examples/basic_operations (#943)
1 parent 8f908cd commit 19d8ab4

File tree

10 files changed

+342
-116
lines changed

10 files changed

+342
-116
lines changed

examples/basic_operations/add_ad_groups.py

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,28 +20,49 @@
2020

2121
import argparse
2222
import sys
23+
from typing import List
2324
import uuid
2425

2526
from google.ads.googleads.client import GoogleAdsClient
2627
from google.ads.googleads.errors import GoogleAdsException
28+
from google.ads.googleads.v20.services.services.ad_group_service import (
29+
AdGroupServiceClient,
30+
)
31+
from google.ads.googleads.v20.services.types.ad_group_service import (
32+
AdGroupOperation,
33+
MutateAdGroupsResponse,
34+
)
35+
from google.ads.googleads.v20.services.services.campaign_service import (
36+
CampaignServiceClient,
37+
)
38+
from google.ads.googleads.v20.resources.types.ad_group import AdGroup
2739

2840

29-
def main(client, customer_id, campaign_id):
30-
ad_group_service = client.get_service("AdGroupService")
31-
campaign_service = client.get_service("CampaignService")
41+
def main(client: GoogleAdsClient, customer_id: str, campaign_id: str) -> None:
42+
ad_group_service: AdGroupServiceClient = client.get_service(
43+
"AdGroupService"
44+
)
45+
campaign_service: CampaignServiceClient = client.get_service(
46+
"CampaignService"
47+
)
3248

3349
# Create ad group.
34-
ad_group_operation = client.get_type("AdGroupOperation")
35-
ad_group = ad_group_operation.create
50+
ad_group_operation: AdGroupOperation = client.get_type("AdGroupOperation")
51+
ad_group: AdGroup = ad_group_operation.create
3652
ad_group.name = f"Earth to Mars cruises {uuid.uuid4()}"
3753
ad_group.status = client.enums.AdGroupStatusEnum.ENABLED
3854
ad_group.campaign = campaign_service.campaign_path(customer_id, campaign_id)
3955
ad_group.type_ = client.enums.AdGroupTypeEnum.SEARCH_STANDARD
4056
ad_group.cpc_bid_micros = 10000000
4157

58+
operations: List[AdGroupOperation] = [ad_group_operation]
59+
4260
# Add the ad group.
43-
ad_group_response = ad_group_service.mutate_ad_groups(
44-
customer_id=customer_id, operations=[ad_group_operation]
61+
ad_group_response: MutateAdGroupsResponse = (
62+
ad_group_service.mutate_ad_groups(
63+
customer_id=customer_id,
64+
operations=operations,
65+
)
4566
)
4667
print(f"Created ad group {ad_group_response.results[0].resource_name}.")
4768

@@ -61,11 +82,13 @@ def main(client, customer_id, campaign_id):
6182
parser.add_argument(
6283
"-i", "--campaign_id", type=str, required=True, help="The campaign ID."
6384
)
64-
args = parser.parse_args()
85+
args: argparse.Namespace = parser.parse_args()
6586

6687
# GoogleAdsClient will read the google-ads.yaml configuration file in the
6788
# home directory if none is specified.
68-
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
89+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
90+
version="v20"
91+
)
6992

7093
try:
7194
main(googleads_client, args.customer_id, args.campaign_id)

examples/basic_operations/add_campaigns.py

Lines changed: 58 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -21,44 +21,77 @@
2121
import argparse
2222
import datetime
2323
import sys
24+
from typing import List
2425
import uuid
2526

2627
from google.ads.googleads.client import GoogleAdsClient
2728
from google.ads.googleads.errors import GoogleAdsException
28-
29-
30-
_DATE_FORMAT = "%Y%m%d"
31-
32-
33-
def main(client, customer_id):
34-
campaign_budget_service = client.get_service("CampaignBudgetService")
35-
campaign_service = client.get_service("CampaignService")
29+
from google.ads.googleads.v20.services.services.campaign_budget_service import (
30+
CampaignBudgetServiceClient,
31+
)
32+
from google.ads.googleads.v20.services.types.campaign_budget_service import (
33+
CampaignBudgetOperation,
34+
MutateCampaignBudgetsResponse,
35+
)
36+
from google.ads.googleads.v20.services.services.campaign_service import (
37+
CampaignServiceClient,
38+
)
39+
from google.ads.googleads.v20.services.types.campaign_service import (
40+
CampaignOperation,
41+
MutateCampaignsResponse,
42+
)
43+
from google.ads.googleads.v20.resources.types.campaign_budget import (
44+
CampaignBudget,
45+
)
46+
from google.ads.googleads.v20.resources.types.campaign import Campaign
47+
48+
49+
_DATE_FORMAT: str = "%Y%m%d"
50+
51+
52+
def main(client: GoogleAdsClient, customer_id: str) -> None:
53+
campaign_budget_service: CampaignBudgetServiceClient = client.get_service(
54+
"CampaignBudgetService"
55+
)
56+
campaign_service: CampaignServiceClient = client.get_service(
57+
"CampaignService"
58+
)
3659

3760
# [START add_campaigns]
3861
# Create a budget, which can be shared by multiple campaigns.
39-
campaign_budget_operation = client.get_type("CampaignBudgetOperation")
40-
campaign_budget = campaign_budget_operation.create
62+
campaign_budget_operation: CampaignBudgetOperation = client.get_type(
63+
"CampaignBudgetOperation"
64+
)
65+
campaign_budget: CampaignBudget = campaign_budget_operation.create
4166
campaign_budget.name = f"Interplanetary Budget {uuid.uuid4()}"
4267
campaign_budget.delivery_method = (
4368
client.enums.BudgetDeliveryMethodEnum.STANDARD
4469
)
4570
campaign_budget.amount_micros = 500000
4671

4772
# Add budget.
73+
campaign_budget_response: MutateCampaignBudgetsResponse
4874
try:
75+
budget_operations: List[CampaignBudgetOperation] = [
76+
campaign_budget_operation
77+
]
4978
campaign_budget_response = (
5079
campaign_budget_service.mutate_campaign_budgets(
51-
customer_id=customer_id, operations=[campaign_budget_operation]
80+
customer_id=customer_id,
81+
operations=budget_operations,
5282
)
5383
)
5484
except GoogleAdsException as ex:
5585
handle_googleads_exception(ex)
5686
# [END add_campaigns]
87+
# We are exiting in handle_googleads_exception so this return is not
88+
# strictly necessary, but it makes static analysis happier.
89+
return
5790

5891
# [START add_campaigns_1]
5992
# Create campaign.
60-
campaign_operation = client.get_type("CampaignOperation")
61-
campaign = campaign_operation.create
93+
campaign_operation: CampaignOperation = client.get_type("CampaignOperation")
94+
campaign: Campaign = campaign_operation.create
6295
campaign.name = f"Interplanetary Cruise {uuid.uuid4()}"
6396
campaign.advertising_channel_type = (
6497
client.enums.AdvertisingChannelTypeEnum.SEARCH
@@ -83,24 +116,28 @@ def main(client, customer_id):
83116
# [END add_campaigns_1]
84117

85118
# Optional: Set the start date.
86-
start_time = datetime.date.today() + datetime.timedelta(days=1)
119+
start_time: datetime.date = datetime.date.today() + datetime.timedelta(
120+
days=1
121+
)
87122
campaign.start_date = datetime.date.strftime(start_time, _DATE_FORMAT)
88123

89124
# Optional: Set the end date.
90-
end_time = start_time + datetime.timedelta(weeks=4)
125+
end_time: datetime.date = start_time + datetime.timedelta(weeks=4)
91126
campaign.end_date = datetime.date.strftime(end_time, _DATE_FORMAT)
92127

93128
# Add the campaign.
129+
campaign_response: MutateCampaignsResponse
94130
try:
131+
campaign_operations: List[CampaignOperation] = [campaign_operation]
95132
campaign_response = campaign_service.mutate_campaigns(
96-
customer_id=customer_id, operations=[campaign_operation]
133+
customer_id=customer_id, operations=campaign_operations
97134
)
98135
print(f"Created campaign {campaign_response.results[0].resource_name}.")
99136
except GoogleAdsException as ex:
100137
handle_googleads_exception(ex)
101138

102139

103-
def handle_googleads_exception(exception):
140+
def handle_googleads_exception(exception: GoogleAdsException) -> None:
104141
print(
105142
f'Request with ID "{exception.request_id}" failed with status '
106143
f'"{exception.error.code().name}" and includes the following errors:'
@@ -125,10 +162,12 @@ def handle_googleads_exception(exception):
125162
required=True,
126163
help="The Google Ads customer ID.",
127164
)
128-
args = parser.parse_args()
165+
args: argparse.Namespace = parser.parse_args()
129166

130167
# GoogleAdsClient will read the google-ads.yaml configuration file in the
131168
# home directory if none is specified.
132-
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
169+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
170+
version="v20"
171+
)
133172

134173
main(googleads_client, args.customer_id)

examples/basic_operations/get_campaigns.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,38 @@
2020

2121
import argparse
2222
import sys
23+
from typing import Iterator, List
2324

2425
from google.ads.googleads.client import GoogleAdsClient
2526
from google.ads.googleads.errors import GoogleAdsException
27+
from google.ads.googleads.v20.services.services.google_ads_service import (
28+
GoogleAdsServiceClient,
29+
)
30+
from google.ads.googleads.v20.services.types.google_ads_service import (
31+
SearchGoogleAdsStreamResponse,
32+
GoogleAdsRow,
33+
)
2634

2735

2836
# [START get_campaigns]
29-
def main(client, customer_id):
30-
ga_service = client.get_service("GoogleAdsService")
37+
def main(client: GoogleAdsClient, customer_id: str) -> None:
38+
ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")
3139

32-
query = """
40+
query: str = """
3341
SELECT
3442
campaign.id,
3543
campaign.name
3644
FROM campaign
3745
ORDER BY campaign.id"""
3846

3947
# Issues a search request using streaming.
40-
stream = ga_service.search_stream(customer_id=customer_id, query=query)
48+
stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream(
49+
customer_id=customer_id, query=query
50+
)
4151

4252
for batch in stream:
43-
for row in batch.results:
53+
rows: List[GoogleAdsRow] = batch.results
54+
for row in rows:
4455
print(
4556
f"Campaign with ID {row.campaign.id} and name "
4657
f'"{row.campaign.name}" was found.'
@@ -60,11 +71,13 @@ def main(client, customer_id):
6071
required=True,
6172
help="The Google Ads customer ID.",
6273
)
63-
args = parser.parse_args()
74+
args: argparse.Namespace = parser.parse_args()
6475

6576
# GoogleAdsClient will read the google-ads.yaml configuration file in the
6677
# home directory if none is specified.
67-
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
78+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
79+
version="v20"
80+
)
6881

6982
try:
7083
main(googleads_client, args.customer_id)

examples/basic_operations/get_responsive_search_ads.py

Lines changed: 46 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,46 +20,67 @@
2020

2121
import argparse
2222
import sys
23+
from typing import List, Optional, Sequence
2324

2425
from google.ads.googleads.client import GoogleAdsClient
2526
from google.ads.googleads.errors import GoogleAdsException
26-
27-
28-
def main(client, customer_id, ad_group_id=None):
29-
ga_service = client.get_service("GoogleAdsService")
30-
31-
query = '''
32-
SELECT ad_group.id, ad_group_ad.ad.id,
33-
ad_group_ad.ad.responsive_search_ad.headlines,
34-
ad_group_ad.ad.responsive_search_ad.descriptions,
35-
ad_group_ad.status FROM ad_group_ad
36-
WHERE ad_group_ad.ad.type = RESPONSIVE_SEARCH_AD
37-
AND ad_group_ad.status != "REMOVED"'''
27+
from google.ads.googleads.v20.common.types.ad_asset import AdTextAsset
28+
from google.ads.googleads.v20.resources.types.ad import Ad
29+
from google.ads.googleads.v20.services.services.google_ads_service import (
30+
GoogleAdsServiceClient,
31+
)
32+
from google.ads.googleads.v20.services.types.google_ads_service import (
33+
SearchGoogleAdsRequest,
34+
SearchGoogleAdsResponse,
35+
)
36+
37+
38+
def main(
39+
client: GoogleAdsClient,
40+
customer_id: str,
41+
ad_group_id: Optional[str] = None,
42+
) -> None:
43+
ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService")
44+
45+
query: str = """
46+
SELECT
47+
ad_group.id,
48+
ad_group_ad.ad.id,
49+
ad_group_ad.ad.responsive_search_ad.headlines,
50+
ad_group_ad.ad.responsive_search_ad.descriptions,
51+
ad_group_ad.status
52+
FROM ad_group_ad
53+
WHERE ad_group_ad.ad.type = RESPONSIVE_SEARCH_AD
54+
AND ad_group_ad.status != REMOVED"""
3855

3956
# Optional: Specify an ad group ID to restrict search to only a given
4057
# ad group.
4158
if ad_group_id:
4259
query += f" AND ad_group.id = {ad_group_id}"
4360

44-
ga_search_request = client.get_type("SearchGoogleAdsRequest")
61+
ga_search_request: SearchGoogleAdsRequest = client.get_type(
62+
"SearchGoogleAdsRequest"
63+
)
4564
ga_search_request.customer_id = customer_id
4665
ga_search_request.query = query
47-
results = ga_service.search(request=ga_search_request)
66+
results: SearchGoogleAdsResponse = ga_service.search(
67+
request=ga_search_request
68+
)
4869

49-
one_found = False
70+
one_found: bool = False
5071

5172
for row in results:
5273
one_found = True
53-
ad = row.ad_group_ad.ad
74+
ad: Ad = row.ad_group_ad.ad
5475
print(
5576
"Responsive search ad with resource name "
5677
f'"{ad.resource_name}", status {row.ad_group_ad.status.name} '
5778
"was found."
5879
)
59-
headlines = "\n".join(
80+
headlines: str = "\n".join(
6081
ad_text_assets_to_strs(ad.responsive_search_ad.headlines)
6182
)
62-
descriptions = "\n".join(
83+
descriptions: str = "\n".join(
6384
ad_text_assets_to_strs(ad.responsive_search_ad.descriptions)
6485
)
6586
print(f"Headlines:\n{headlines}\nDescriptions:\n{descriptions}\n")
@@ -68,9 +89,10 @@ def main(client, customer_id, ad_group_id=None):
6889
print("No responsive search ads were found.")
6990

7091

71-
def ad_text_assets_to_strs(assets):
92+
def ad_text_assets_to_strs(assets: Sequence[AdTextAsset]) -> List[str]:
7293
"""Converts a list of AdTextAssets to a list of user-friendly strings."""
73-
s = []
94+
s: List[str] = []
95+
asset: AdTextAsset
7496
for asset in assets:
7597
s.append(f"\t {asset.text} pinned to {asset.pinned_field.name}")
7698
return s
@@ -96,11 +118,13 @@ def ad_text_assets_to_strs(assets):
96118
required=False,
97119
help="The ad group ID. ",
98120
)
99-
args = parser.parse_args()
121+
args: argparse.Namespace = parser.parse_args()
100122

101123
# GoogleAdsClient will read the google-ads.yaml configuration file in the
102124
# home directory if none is specified.
103-
googleads_client = GoogleAdsClient.load_from_storage(version="v20")
125+
googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage(
126+
version="v20"
127+
)
104128

105129
try:
106130
main(

0 commit comments

Comments
 (0)