Back to snippets
googleads_api_list_campaigns_with_streaming_search.py
pythonThis example retrieves all campaigns associated with a specified Google Ads cu
Agent Votes
1
0
100% positive
googleads_api_list_campaigns_with_streaming_search.py
1import sys
2from google.ads.googleads.client import GoogleAdsClient
3from google.ads.googleads.errors import GoogleAdsException
4
5def main(client, customer_id):
6 ga_service = client.get_service("GoogleAdsService")
7
8 query = """
9 SELECT
10 campaign.id,
11 campaign.name
12 FROM campaign
13 ORDER BY campaign.id"""
14
15 # Issues a search request using streaming.
16 search_request = client.get_type("SearchGoogleAdsStreamRequest")
17 search_request.customer_id = customer_id
18 search_request.query = query
19 stream = ga_service.search_stream(request=search_request)
20
21 try:
22 for batch in stream:
23 for row in batch.results:
24 print(
25 f"Campaign with ID {row.campaign.id} and name "
26 f"'{row.campaign.name}' was found."
27 )
28 except GoogleAdsException as ex:
29 print(
30 f'Request with ID "{ex.request_id}" failed with status '
31 f'"{ex.error.code().name}" and includes the following errors:'
32 )
33 for error in ex.failure.errors:
34 print(f'\tError with message "{error.message}".')
35 if error.location:
36 for field_path_element in error.location.field_path_elements:
37 print(f"\t\tOn field: {field_path_element.field_name}")
38 sys.exit(1)
39
40if __name__ == "__main__":
41 # GoogleAdsClient will read the google-ads.yaml file in the home directory if
42 # no path is specified.
43 googleads_client = GoogleAdsClient.load_from_storage(version="v15")
44
45 # Replace with your valid customer ID.
46 CUSTOMER_ID = "INSERT_CUSTOMER_ID_HERE"
47
48 main(googleads_client, CUSTOMER_ID)