get_camp.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python
  2. # Copyright 2020 Google LLC
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # https://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """This example illustrates how to get all campaigns.
  16. To add campaigns, run add_campaigns.py.
  17. """
  18. import argparse
  19. import sys
  20. from google.ads.googleads.client import GoogleAdsClient
  21. from google.ads.googleads.errors import GoogleAdsException
  22. def main(client, customer_id):
  23. ga_service = client.get_service("GoogleAdsService")
  24. query = """
  25. SELECT
  26. campaign.id,
  27. campaign.name
  28. FROM campaign
  29. ORDER BY campaign.id"""
  30. # Issues a search request using streaming.
  31. response = ga_service.search_stream(customer_id=customer_id, query=query)
  32. for batch in response:
  33. for row in batch.results:
  34. print(
  35. f"Campaign with ID {row.campaign.id} and name "
  36. f'"{row.campaign.name}" was found.'
  37. )
  38. if __name__ == "__main__":
  39. # GoogleAdsClient will read the google-ads.yaml configuration file in the
  40. # home directory if none is specified.
  41. googleads_client = GoogleAdsClient.load_from_storage(version="v7")
  42. parser = argparse.ArgumentParser(
  43. description="Lists all campaigns for specified customer."
  44. )
  45. # The following argument(s) should be provided to run the example.
  46. parser.add_argument(
  47. "-c",
  48. "--customer_id",
  49. type=str,
  50. required=True,
  51. help="The Google Ads customer ID.",
  52. )
  53. args = parser.parse_args()
  54. try:
  55. main(googleads_client, args.customer_id)
  56. except GoogleAdsException as ex:
  57. print(
  58. f'Request with ID "{ex.request_id}" failed with status '
  59. f'"{ex.error.code().name}" and includes the following errors:'
  60. )
  61. for error in ex.failure.errors:
  62. print(f' Error with message "{error.message}".')
  63. if error.location:
  64. for field_path_element in error.location.field_path_elements:
  65. print(f"\t\tOn field: {field_path_element.field_name}")
  66. sys.exit(1)