Posts tagged with python

So I've queried the location_view resource using the code shown below. I've tried something similar using the geographic_view, but it also leads to the same problem. This problem is that metrics like average_cost or average_cpc are ~2800000. Now this obviously can't be correct. I was wondering if anyone has had a similar problem or if maybe, the actual value is multiplied by a factor of 1M or something

from google.ads.googleads.client import GoogleAdsClient credentials = { "developer_token": "xx", "refresh_token": "xx", "client_id":"xx", "client_secret": "xx"}  client = GoogleAdsClient.load_from_dict(credentials) query = """ SELECT location_view.resource_name, segments.date, metrics.average_cost, metrics.average_cpc, metrics.clicks, metrics.conversions, metrics.cost_micros, metrics.cost_per_conversion, metrics.impressions, metrics.interactions, metrics.interaction_rate, campaign.id, campaign.name, campaign.end_date, campaign.start_date FROM location_view WHERE segments.date DURING LAST_30_DAYS""" ga_service = client.get_service("GoogleAdsService") search_request = client.get_type("SearchGoogleAdsStreamRequest") search_request.customer_id = "xx" search_request.query = query test = [] response = ga_service.search_stream(search_request) for batch in response:         for row in batch.results:            test.append(row)  

I am trying to access the metrics for client accounts using the Google Ads API, through the Python client.

Currently I'm using a modified version of the get_campaign_stats_to_csv.py example, with the query:

import datetime last_three_days = datetime.datetime.today() - datetime.timedelta(days=3) query = """     SELECT          customer.descriptive_name,          metrics.cost_micros      FROM customer      WHERE          segments.date > '{last_three_days}'          AND segments.date <= '{today}'""".format(             last_three_days=last_three_days.strftime('%Y-%m-%d'),             today=datetime.datetime.today().strftime('%Y-%m-%d')) 

It requires the commandline argument --customer_id= of the account we're reporting on, used as follows:

search_request.customer_id = customer_id # e.g., '--customer_id=1234567890' 

The problem is that when I use my Manager account customer id 1234567890, I get the error:

error_code {     query_error: REQUESTED_METRICS_FOR_MANAGER   }   message: "Metrics cannot be requested for a manager account. To retrieve metrics, issue  separate requests against each client account under the manager account." } 

Which I assume means using the client id. But when I use the client ID 0987654321, I get the error:

error_code {     authorization_error: USER_PERMISSION_DENIED   }   message: "User doesn\'t have permission to access customer. Note: If you\'re accessing a  client customer, the manager\'s customer id must be set in the \'login-customer-id\'  header. See https://developers.google.com/google-ads/api/docs/concepts/call-structure#cid" } 

The link in the error message leads to the following header:

Which brings me back to square one, where the API spits the dummy when I use the Manager Account ID.

I've checked out this stack overflow question, but I think we're having different problems, as all my accounts have the red 'TEST ACCOUNT' flag next to them.

As a final note: there are two test client accounts, both which I've set up with quasi campaigns.

I'm trying to work with google ads API I got all the authentication in place on yaml file. and I'm ready to start requesting info from the Google API

I downloaded the generate_keyword_ideas.py file from google GitHub this is the file here: https://github.com/googleads/google-ads-python/blob/ee2c059498d5679a0d1d9011f3795324439fad7c/examples/planning/generate_keyword_ideas.py

in short the file function takes all these inputs

def main(client, customer_id, location_ids, language_id, keyword_texts, page_url

)

when i run the main file i get this error message:

usage: main.py [-h] -c CUSTOMER_ID [-k KEYWORD_TEXTS [KEYWORD_TEXTS ...]]            [-l LOCATION_IDS [LOCATION_IDS ...]] [-i LANGUAGE_ID]            [-p PAGE_URL] main.py: error: the following arguments are required: -c/--customer_id 

I don't know what kind of input customer_id takes, coz I got my 10 digits id from google ads and I thought that's what it is but its not, and also what is -c? and how can I fill both of them?, iv been trying for a long time and nothing is working .. please help thanks

I'm wanting to convert the GoogleAdsRows to json (to then put into a dataframe). when using proto.Message.to_json, i do get json, but it also returns fields that I never queried.

here's the code i'm using (I declare the credentials right before, but left that out so i can post)

import proto from google.ads.googleads.client import GoogleAdsClient credentials = {     "developer_token": developer_token,     "refresh_token": refresh_token,     "client_id": client_id,     "client_secret": client_secret,     "login_customer_id": login_customer_id} client = GoogleAdsClient.load_from_dict(credentials) ga_service = client.get_service("GoogleAdsService",version='v6') query = """         SELECT              campaign.id,             segments.device                              FROM campaign          WHERE segments.date = '20210405'         LIMIT 10 """ response = ga_service.search_stream(customer_id=customer_id, query=query) for batch in response:     for row in batch.results:         newrow = proto.Message.to_json(row,preserving_proto_field_name=True)         print(newrow) 

returns (partial shown):

    "click_type": 0,     "conversion_action_category": 0,     "conversion_attribution_event_type": 0,     "conversion_lag_bucket": 0,     "conversion_or_adjustment_lag_bucket": 0,     "day_of_week": 0,     "external_conversion_source": 0,     "hotel_check_in_day_of_week": 0,     "hotel_date_selection_type": 0,     "hotel_rate_type": 0,     "hotel_price_bucket": 0,     "month_of_year": 0,     "placeholder_type": 0,     "product_channel": 0,     "product_channel_exclusivity": 0,     "product_condition": 0, 

so, I never ask for any of the fields above, only campaign.id and segments.device, yet it returns 36 fields... any idea on how to just return the fields I requested? If I print(row) directly, i can see that it only returns the fields requested in the query, so i have no idea where it is grabbing these extra fields from.

thanks!

Edit: I tinkered around with the response a bit more and now I have some decent results, however this seems very complex considering all i want to do is take protobuf -> DataFrame..

results = [] for batch in response:     for row in batch.results:         pbrow = proto.Message.pb(row)         newrow = json_format.MessageToJson(pbrow)         evalrow = eval(newrow)         df = pd.json_normalize(evalrow)         results.append(df) print(results) 

Output (made-up campaigns/customerids):

[                      campaign.resourceName campaign.id segments.device 0  customers/1234567891/campaigns/098765432   098765432         DESKTOP,                       campaign.resourceName campaign.id segments.device 0  customers/1234567891/campaigns/987654321   987654321          MOBILE,                       campaign.resourceName campaign.id segments.device 0  customers/1234567891/campaigns/876543210   876543210          TABLET,                       campaign.resourceName campaign.id segments.device 0  customers/1234567891/campaigns/765432109   765432109         DESKTOP,                       campaign.resourceName campaign.id segments.device ] 

is there any way to simplify this? what the heck am i missing that this needs 5 transformations to combine the data stream?