Dear Google Ads API Team,
I am trying to run several Python scripts to get dashboards or other infos from my campaigns, but had no success in almost every one.
Also, I've already been conceived as an Administrator in my company's MCC and in the specific Account which we want to be the reference for our scripts and to get information from.
To run my scripts, I've reunited MCC_id, Account_id, Client_id, Client_secret, refresh_token and developer_token like this:
- MCC_id: In the google ads interface
- Account_id: Also in google ads interface, but logged in the account we want;
- Client_id: Google ads interface from the specific company
- client_secret/secret_key and refresh token: Logging into the OAuth interface.
So, when i ran this Python script, it actually worked and we got the name of all campaigns:
############################
import argparse
import sys
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
from dotenv import dotenv_values
config = dotenv_values(".env")
credentials = {
"developer_token": config["developer_token"],
"refresh_token": config["refresh_token"],
"client_id": config["client_id"],
"client_secret": config["client_secret"],
"account_id": config["account_id"],
"mcc_id": config["mcc_id"],
"use_proto_plus": True
}
def main(client, customer_id):
ga_service = client.get_service("GoogleAdsService")
query = """
SELECT
campaign.id,
campaign.name
FROM campaign
ORDER BY campaign.id"""
# Issues a search request using streaming.
stream = ga_service.search_stream(customer_id=customer_id, query=query)
for batch in stream:
for row in batch.results:
print(
f"Campaign with ID {row.campaign.id} and name "
f'"{row.campaign.name}" was found.'
)
if __name__ == "__main__":
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
google_ads_client = GoogleAdsClient.load_from_dict(credentials, version="v13")
customer_id = config["account_id"]
try:
main(google_ads_client, customer_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
############################
But when i tried to catch the data from a campaign using:
###########################
DEVELOPER_TOKEN = "xxxxxxxx-xxxxxxxxxxxxx"
PATH_TO_CREDENTIALS = "caminhoJson1205.json"
CUSTOMER_ID = "xxxxxxxxx"
def get_google_ads_data(credentials_path, developer_token, customer_id):
try:
# Autenticação
credentials = service_account.Credentials.from_service_account_file(credentials_path)
credentiaels = credentials.with_scopes(['https://www.googleapis.com/auth/adwords'])
# Criar cliente do Google Ads
google_ads_client = GoogleAdsClient(credentials=credentials, developer_token=developer_token)
# Construir a consulta
query = f"""
SELECT
campaign.id
# ad_group.id,
# ad.id,
# ad.type,
# ad.headline,
# ad.description,
# metrics.impressions,
# metrics.clicks,
# metrics.average_cpc
FROM
ad
WHERE
segments.date DURING LAST_7_DAYS
AND metrics.impressions > 0
"""
ga_service = google_ads_client.get_service("GoogleAdsService")
# Executar a consulta
response = ga_service.search_stream(customer_id=customer_id, query=query)
# Exibir resultados
for batch in response:
for row in batch.results:
print(f"Ad ID: {row.ad.id.value}, Headline: {row.ad.headline.value}, Impressions: {row.metrics.impressions.value}")
except Exception as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
get_google_ads_data(PATH_TO_CREDENTIALS, DEVELOPER_TOKEN, CUSTOMER_ID)
############################
It didn't work.
Important to say we also created a service account (according to what GPT told us), but even when we tried to connect the service account to the project, it didn't work as well.
So please, help us step-by-step on how to properly catch campaigns using Python.
Hello,
Thank you for reaching out to Google Ads API Forum.
It appears that your concern is with regards to getting the campaign data when using your service account credentials. With this, could you try referring to this API documentation (https://developers.google.com/google-ads/api/docs/oauth/service-accounts) that discusses how to access the Google Ads API with service accounts? Please also note that a service account can only impersonate users (email addresses) in the same Google Workspace (https://workspace.google.com/).
Additionally, please refer to this guide (https://developers.google.com/google-ads/api/docs/client-libs/python/oauth-service) that will walk you through how to set up OAuth2 for API access using your own credentials with service accounts. These steps only need to be done once, unless you revoke or delete your OAuth2 credentials.
Furthermore, it seems that the query for your request using service account credentials is invalid. That said, you may use the Query Builder (https://developers.google.com/google-ads/api/fields/v13/overview_query_builder?hl=en) and Query Validator (https://developers.google.com/google-ads/api/fields/v13/query_validator?hl=en) for creating and validating your queries.
For our team to further check why it did not work on your end, could you share with us the complete request and response logs with request ID and request header generated on your end? You may send it privately via the Reply to author option. If this option is not available, you may send the details directly to our googleadsa...@google.com alias instead.
If you haven't enabled logging yet, it can be enabled by navigating to the Client libraries > Python > Logging documentation (https://developers.google.com/google-ads/api/docs/best-practices/logging#python), which you can access from this link.
Reference Links:
Regards,
![]() |
Google Ads API Team |