googleads / googleads-python-lib

The Python client library for Google's Ads APIs
Apache License 2.0
683 stars 975 forks source link

Google Ad Manager API Custom Dimensions Using saved_report_query #539

Closed PGLaurens closed 9 months ago

PGLaurens commented 9 months ago

We have 2000+ key value pairs in use that we need to report on and pull as CUSTOM_DIMENSIONS via the API into BigQuery.

I am trying to add CUSTOM_DIMENSIONS into a report_query in Python, but struggling with how to add all the different dimensions and combinations + the ID's and attributes.

The other method is to use a report that is saved in the Google Ad Manager UI and then by using its ID, to pull that, but not sure if the code is actually producing the same report or data as in the saved report.

Here is the code I am running for the saved_report:

  # Import appropriate modules from the client library.
  import tempfile
  import pandas as pd  # Add this import statement

  from googleads import ad_manager
  from googleads import errors

  SAVED_QUERY_ID = '14311764884'

  def main(client, saved_query_id):
    # Initialize appropriate service.
    report_service = client.GetService('ReportService', version='v202311')

    # Initialize a client object.
    client = ad_manager.AdManagerClient.LoadFromStorage("googleads.yaml")

    # Initialize a DataDownloader.
    report_downloader = client.GetDataDownloader(version='v202311')

    # Create statement object to filter for an order.
    statement = (ad_manager.StatementBuilder(version='v202311')
                 .Where('id = :id')
                 .WithBindVariable('id', int(saved_query_id))
                 .Limit(1))

    response = report_service.getSavedQueriesByStatement(
        statement.ToStatement())

    if 'results' in response and len(response['results']):
      saved_query = response['results'][0]

      if saved_query['isCompatibleWithApiVersion']:
        report_job = {}

        # Set report query and optionally modify it.
        report_job['reportQuery'] = saved_query['reportQuery']

        try:
          # Run the report and wait for it to finish.
          report_job_id = report_downloader.WaitForReport(report_job)
        except errors.AdManagerReportError as e:
          print('Failed to generate report. Error was: %s' % e)
        # Change to your preferred export format.
        export_format = 'CSV_DUMP'

        report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)

        # Download report data.
        report_downloader.DownloadReportToFile(
            report_job_id, export_format, report_file)

        report_file.close()

        # Display results.
        print('Report job with id "%s" downloaded to:\n%s' % (
            report_job_id, report_file.name))
      else:
        print('The query specified is not compatible with the API version.')

        # Display results.
        print('Report job with id "%s" downloaded to:\n%s' % (
          report_job_id, report_file.name))

      # Use pandas to read the CSV file into a DataFrame
        df = pd.read_csv(report_file.name, compression='gzip')

      # Display DataFrame information
        print('\nDataFrame Information:')
        print('Dimensions:', df.shape)
        print('Columns:', df.columns)
        print('\nDataFrame Sample:')
        print(df.head())

  if __name__ == '__main__':
    # Initialize client object.
    ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage("googleads.yaml")
    main(ad_manager_client, SAVED_QUERY_ID)

I would appreciate any help, especially to view the dataframe or with mistakes in the code.

christopherseeley commented 9 months ago

The other method is to use a report that is saved in the Google Ad Manager UI and then by using its ID, to pull that, but not sure if the code is actually producing the same report or data as in the saved report.

If you run a report by ID then it will be the same data. The export format CSV_DUMP does have some formatting differences you can see here: https://developers.google.com/ad-manager/api/reference/v202308/ReportService.ExportFormat

If you are seeing a data discrepancy, you can reach out on that Ad Manager API forum: https://groups.google.com/g/google-doubleclick-for-publishers-api