DoubleClickBidManager API no data retrieved

I've created a project within Google Cloud, enabled DV360 and DoubleClick Bid Manager APIs, created oAuth 2.0 Client IDs and credentials and have dowloaded the JSON client secret which I have attached to my project root. In my python code, I am trying to retrieve data (any data) from a queries.create method then loop until the report status becomes AVAILABLE using `state = query.get('metadata', {}).get('status', {}).get('state')` but the ReportStatus returns blank continuously. This is my python code :

import logging
import csv
import time
import urllib.request
import os
import pickle

from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build


API_VERSION = 'v2'
ADVERTISER_ID = '*****'
SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']

# Set up the credentials
creds = None

if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'/Users/directory to root', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)

# Build the doubleclickbidmanager API client
service = build('doubleclickbidmanager', API_VERSION, credentials=creds)


# Set up logging
logging.basicConfig(level=logging.DEBUG)

# Create a query
query_body = {
"metadata": {
"title": "Basic Report",
"dataRange": {
"range": "LAST_7_DAYS"
},
"format": "CSV"
},
"params": {
"type": "STANDARD",
"groupBys": ["FILTER_PARTNER"],
"metrics": ["METRIC_IMPRESSIONS"]
},
"schedule": {
"frequency": "ONE_TIME"
}
}


try:
# Run the query
query_create = service.queries().create(body=query_body).execute()
print(f'Query creation response: {query_create}')

query_id = query_create['queryId']

logging.debug(f'Query ID: {query_id}')

logging.debug("Query executed")

# Wait for the report to be generated
report_available = False
num_retries = 0
while not report_available and num_retries < 100:
try:
query = service.queries().get(queryId=query_id).execute()
print(f'Query data: {query}')
print(f'Query metadata: {query.get("metadata")}')
except Exception as e:
print('Error occurred: ', e)

if 'error' in query:
logging.error(f'Error in query: {query.get("error")}')

print(f'Query retrieval response: {query}')

logging.debug(f'Query status: {query["metadata"]}, query ID: {query["queryId"]}')
logging.debug(f'ReportStatus: {query.get("metadata", {}).get("status", {})}')

# Check if report is ready or has failed
state = query.get('metadata', {}).get('status', {}).get('state')
if state == 'DONE':
report_available = True
elif state == 'FAILED':
logging.error("Report generation failed.")
break
else:
logging.debug("Waiting 30 seconds before checking again")
time.sleep(30)
num_retries += 1

if not report_available:
logging.error('Report did not become available after 100 retries. Aborting.')
else:
# Get the Google Cloud Storage path for the report
google_cloud_storage_path = query.get('metadata', {}).get('googleCloudStoragePath', '')

if google_cloud_storage_path:
# Download the report as CSV
report_file_name = 'campaign_overview_report.csv'
urllib.request.urlretrieve(google_cloud_storage_path, report_file_name)
print("Report downloaded.")
else:
print("Google Cloud Storage path not found for the report.")

except Exception as ex:
print('Exception occurred during query execution: ', ex)

Why is my reportStatus continuously returning blank? I am set as the 'Owner' of the project so permissions wouldn't be an issue. Even if there is no data, the status should surely update? Am I doing something wrong?

 

0 1 696
1 REPLY 1

Hi @PierrieK,

Welcome to the Google Cloud Community!

You can try the following troubleshooting options:

  1. You can refer to this Github Repository about Bid Manager REST API v2 Python Samples. It contains Prerequisites, Setup Authentication, as well as running an example. 
  2. You should also check your Cloud Logging to pin point where the error is coming from, as well as monitoring the logs.
  3. I noticed in your Stack Overflow post that this line seems to be what's causing the problem. There seems to be an error with the way the string is constructed. You may notice that the " )}' " is green, which might indicate the problem.
    logging.debug(f'ReportStatus: {query.get("metadata", {}).get("status", {})}')
  4. You can also get in touch with Google Cloud Support if the above options don't work.

Let me know if it helped, thanks!

Top Labels in this Space