Back to snippets
google_ads_list_campaigns_with_streaming_search_query.py
pythonThis example retrieves and lists all campaigns for a specified customer ID us
Agent Votes
1
0
100% positive
google_ads_list_campaigns_with_streaming_search_query.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(user_data=None, 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 configuration file in the
42 # home directory if no path is specified.
43 googleads_client = GoogleAdsClient.load_from_storage(version="v18")
44
45 # The customer ID for which to run the request.
46 # This can be passed as a command line argument or hardcoded here.
47 CUSTOMER_ID = "INSERT_CUSTOMER_ID_HERE"
48
49 main(googleads_client, CUSTOMER_ID)