def get_city_and_country_names(google_source, ads_client):
df_orig = pd.DataFrame(google_source)
#df_orig has data from the main report
df_orig['country_id'] = 'geoTargetConstants/' + df_orig['country_id'].astype(str)
gtc_service = ads_client.get_service("GeoTargetConstantService", version="v6")
location_names = ads_client.get_type( "SuggestGeoTargetConstantsRequest",version="v6").GeoTargets()
location_names.geo_target_constants.extend(df_orig['city_id'].unique())
results = gtc_service.suggest_geo_target_constants(geo_targets=location_names)
cities = {}
countries = {}
for suggestion in results.geo_target_constant_suggestions:
geo_target_constant = suggestion.geo_target_constant
cities[geo_target_constant.resource_name] = geo_target_constant.name
for geo_target_constant_parents in suggestion.geo_target_constant_parents:
if geo_target_constant_parents.target_type == "Country":
countries[geo_target_constant_parents.resource_name] = geo_target_constant_parents.name
df_city = pd.DataFrame(cities.items(),columns=['city_id', 'city'])
df_country = pd.DataFrame(countries.items(),columns=['country_id', 'country'])
df = df_orig.merge(df_city, how='left', on=['city_id']).merge(df_country, how='left', on=['country_id'])
return df
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
def get_city_and_country_names(google_source, ads_client):
df_orig = pd.DataFrame(google_source)
#df_orig has data from the main report
df_orig['country_id'] = 'geoTargetConstants/' + df_orig['country_id'].astype(str)
df_unique=df_orig[['city_id','country_id']].drop_duplicates(keep='first')
cities = {}
countries = {}
i=0
for df_temp in chunker(df_unique,24):
print(i)
gtc_service = ads_client.get_service("GeoTargetConstantService", version="v8")
location_names = ads_client.get_type("SuggestGeoTargetConstantsRequest", version="v8").GeoTargets()
location_names.geo_target_constants.extend(df_temp['city_id'].unique())
results = gtc_service.suggest_geo_target_constants(location_names)
for suggestion in results.geo_target_constant_suggestions:
geo_target_constant = suggestion.geo_target_constant
temp_cities = {}
temp_cities[geo_target_constant.resource_name] = geo_target_constant.name
cities.update(temp_cities)
for geo_target_constant_parents in suggestion.geo_target_constant_parents:
if geo_target_constant_parents.target_type == "Country":
temp_countries = {}
temp_countries[geo_target_constant_parents.resource_name] = geo_target_constant_parents.name
countries.update(temp_countries)
i=i+1
df_city = pd.DataFrame(cities.items(),columns=['city_id', 'city'])
df_country = pd.DataFrame(countries.items(),columns=['country_id', 'country'])
df = df_orig.merge(df_city, how='left', on=['city_id']).merge(df_country, how='left', on=['country_id'])
return df
|
||||||
Hi Matt, thanks for responding.
Adding complete code below to show the requests made.
######## Python3 Code --> Google Ads API v8 #######
######## Kindly note, I have executed this on production to align the new api version: pip install google-ads==12.0.0 #######
import json
import logging
from datetime import date, datetime, timedelta
import pandas as pd
from google.ads.googleads.client import GoogleAdsClient
from typing import Any, Dict, List, Optional
logger = logging.getLogger()
end_date = (date.today() - timedelta(days=1)).strftime("%Y%m%d")
start_date = (date.today() - timedelta(days=1)).strftime("%Y%m%d")
print("start_date: ", start_date)
print("end_date: ", end_date)
def get_all_accounts(ads_client, login_customer_id: int) -> Dict[str, int]:
ads_service_client = ads_client.get_service("GoogleAdsService", version="v8")
query = """
SELECT
customer_client.level,
customer_client.manager,
customer_client.descriptive_name,
customer_client.id
FROM customer_client
WHERE customer_client.level = 1 and customer_client.id !='__________' """
response = ads_service_client.search(customer_id=str(login_customer_id), query=query)
accounts: Dict[str, int] = dict()
for google_ads_row in response:
customer_client = google_ads_row.customer_client
accounts[customer_client.descriptive_name] = customer_client.id
return accounts
def get_account_data(ads_client, account_name: str, account_id: int, start_dt: str, end_dt: str) -> \
List[Dict[str, Any]]:
ads_service_client = ads_client.get_service("GoogleAdsService", version="v8")
campaign_status_enum_client = ads_client.get_type('CampaignStatusEnum', version="v8")
ad_network_type_enum_client = ads_client.get_type('AdNetworkTypeEnum', version="v8")
day_of_week_enum_client = ads_client.get_type('DayOfWeekEnum', version="v8")
device_enum_client = ads_client.get_type('DeviceEnum', version="v8")
report_query = f"""
SELECT
campaign.id, campaign.name, campaign.status,
segments.date, segments.day_of_week, segments.ad_network_type, segments.device,
metrics.clicks, metrics.impressions, metrics.cost_micros,
metrics.conversions, metrics.conversions_value, metrics.ctr, metrics.interactions,
metrics.video_views, metrics.video_view_rate,
segments.geo_target_city, geographic_view.country_criterion_id
FROM geographic_view
WHERE campaign.status in('ENABLED', 'PAUSED')
AND segments.date BETWEEN '{start_dt}' AND '{end_dt}' """
report_response = ads_service_client.search_stream(customer_id=str(account_id), query=report_query)
results: List[Dict[str, Any]] = list()
for batch in report_response:
for row in batch.results:
campaign, metrics, segments, geographic_view = row.campaign, row.metrics, row.segments, row.geographic_view
info: Dict[str, Any] = {
'account_name': account_name,
'account_id': account_id,
'campaign_id': campaign.id,
'campaign': campaign.name,
'day': segments.date,
'day_of_week': str(day_of_week_enum_client.DayOfWeek(segments.day_of_week)).split(".")[1].replace('.', '').strip().title(),
'clicks': metrics.clicks,
'impressions': metrics.impressions,
'cost': metrics.cost_micros,
'conversions': metrics.conversions,
'total_conv_value': metrics.conversions_value,
'interactions': metrics.interactions,
'ctr': str(round(metrics.ctr * 100, 2)) + "%",# converting to percentage as earlier it was in percentage
'network2': str(ad_network_type_enum_client.AdNetworkType(segments.ad_network_type)).split(".")[1].replace('.', '').strip(),
'campaign_state': str(campaign_status_enum_client.CampaignStatus(campaign.status)).split(".")[1].replace('.', '').strip().lower(),
'video_views': metrics.video_views,
'video_view_rate': metrics.video_view_rate,
'city_id': segments.geo_target_city,
'country_id':geographic_view.country_criterion_id,
'device_type': str(device_enum_client.Device(segments.device)).split(".")[1].replace('.', '').strip().lower()
}
results.append(info)
return results
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
def get_city_and_country_names(google_source, ads_client):
df_orig = pd.DataFrame(google_source)
df_orig['country_id'] = 'geoTargetConstants/' + df_orig['country_id'].astype(str)
df_unique=df_orig[['city_id','country_id']].drop_duplicates(keep='first')
cities = {}
countries = {}
i=0
for df_temp in chunker(df_unique,24):
print(i)
gtc_service = ads_client.get_service("GeoTargetConstantService", version="v8")
location_names = ads_client.get_type("SuggestGeoTargetConstantsRequest", version="v8").GeoTargets()
print("After GeoTargets")
print(location_names)
location_names.geo_target_constants.extend(df_temp['city_id'].unique())
print("After list of city_id")
print(location_names)
results = gtc_service.suggest_geo_target_constants(location_names) #Error in this command
for suggestion in results.geo_target_constant_suggestions:
geo_target_constant = suggestion.geo_target_constant
temp_cities = {}
temp_cities[geo_target_constant.resource_name] = geo_target_constant.name
cities.update(temp_cities)
for geo_target_constant_parents in suggestion.geo_target_constant_parents:
if geo_target_constant_parents.target_type == "Country":
temp_countries = {}
temp_countries[geo_target_constant_parents.resource_name] = geo_target_constant_parents.name
countries.update(temp_countries)
i=i+1
df_city = pd.DataFrame(cities.items(),columns=['city_id', 'city'])
df_country = pd.DataFrame(countries.items(),columns=['country_id', 'country'])
df = df_orig.merge(df_city, how='left', on=['city_id']).merge(df_country, how='left', on=['country_id'])
return df
def main():
# read token
try:
config_dict: Optional[Dict[str, Any]] = json.loads(config.get("__________________________"))
if not config_dict:
raise Exception("No config found.")
ads_client = GoogleAdsClient.load_from_dict(config_dict)
login_customer_id: int = int(config_dict['login_customer_id'])
accounts = get_all_accounts(ads_client, login_customer_id)
google_campaign_report_source = []
for acc_name, acc_id in accounts.items():
account_reports = get_account_data(ads_client, acc_name, acc_id, start_date, end_date)
google_campaign_report_source += account_reports
# Get country and city name
df = get_city_and_country_names(google_campaign_report_source, ads_client)
df.to_csv('final_report.csv',index=False)
except Exception as e:
logger.info(e)
print(e)
raise
if __name__ == "__main__":
main()
Hello,
Thank you for getting back to us.
However, I'm afraid that we will be needing the complete API logs (request and response with request-id) instead of those trace logs provided. Since you're using the Python client library, you can enable logging via this guide.
Once those API logs are available, please send the those details via the Reply privately to author option. If this option is not available, you may send the details directly to our googleadsa...@google.com alias instead.
Regards,
|
||||||
|
||||||
Hello,
Thanks for getting back to us.
As previously mentioned by Matt, the only way to get the location name is via the name field from the geo_target_constant. Allow me to raise a feature request for this (subject for review); however, before doing so, can you share to us your business use case as to how this feature will be beneficial on your end?
Regards,
Reminder: Share your feedback about the Google Ads (AdWords) API! Take the 2021 Google Ads API and AdWords API Annual Survey
|
||||||
This message was sent to the following 2 people: cv, Google Ads API Forum Advisor. Replying to this email will notify them.
Google Ads API Forum Advisor was added to the conversation by adwor...@googlegroups.com
Hello,
Thanks for getting back to us.
As previously mentioned by Matt, the only way to get the location name is via the name field from the geo_target_constant. Allow me to raise a feature request for this (subject for review); however, before doing so, can you share to us your business use case as to how this feature will be beneficial on your end?
Regards,
Reminder: Share your feedback about the Google Ads (AdWords) API! Take the 2021 Google Ads API and AdWords API Annual Survey
https://www.gstatic.com/images/branding/product/1x/googleg_64dp.png Mark Kevin Albios Google Ads API Team https://google-dev-relations.my.salesforce.com/servlet/servlet.ImageServer?oid=00D1U000001174p&esid=0184Q00001Ey2j2&from=ext
ref:_00D1U1174p._5004Q2NU3zw:ref --
--
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
Also find us on our blog:
https://googleadsdeveloper.blogspot.com/
=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
You received this message because you are subscribed to the Google
Groups "AdWords API and Google Ads API Forum" group.
To post to this group, send email to adwor...@googlegroups.com
To unsubscribe from this group, send email to
adwords-api...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/adwords-api?hl=en
---
You received this message because you are subscribed to the Google Groups "AdWords API and Google Ads API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to adwords-api...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/adwords-api/gPeNg000000000000000000000000000000000000000000000R2YHP90007rJdP20QvCK6qujBKiWVA%40sfdc.net.
On Sat, Nov 20, 2021 at 06:34 AM, "cv" <chirag....@gmail.com> wrote:
Hi Matt,
Yes, I was using same only.
But to get name from id in geographics_view it is expensive.
I need to call geo_target_constant resource search operation for every id, and not only it is for one field it is across country, city, state fields..
On Friday, 19 November 2021 at 22:36:59 UTC+5:30 adsapi wrote:
Hello,
You can use the ID to get the Geotarget name with the geo_constant_name resource with the name attribute.
Regards,
Matt
Google Ads API Team
Reminder: Share your feedback about the Google Ads (AdWords) API! Take the 2021 Google Ads API and AdWords API Annual Survey
|
||||||
Hi,
If you're checking on the status of the feature request to include the name field for geo in the location_view, this is still not supported in the API.
Kindly note that we're unable to provide a timeline on when it will be available in the API. You may continue to keep an eye on our blog post (https://ads-developers.googleblog.com/search/label/google_ads_api) and to the release notes (https://developers.google.com/google-ads/api/docs/release-notes) for the latest updates in the API.
Regards,
![]() |
Google Ads API Team |