Package: google-ads-api-report-fetcher
Google Ads API Report Fetcher (gaarf)Python version of Google Ads API Report Fetcher tool a.k.a.gaarf.
Please see the full documentation in the rootREADME.Getting startedPrerequisitesPython 3.9+pip installedGoogle Ads API enabledgoogle-ads.yamlfile. Learn how to create onehere.Installation and runningcreate virtual environment and install the toolpython3 -m venv gaarf
source gaarf/bin/activate
pip install google-ads-api-report-fetcherinstall the latest development version withpip install -e git+https://github.com/google/ads-api-report-fetcher.git#egg=google-ads-api-report-fetcher\&subdirectory=pyVersions of the librarygoogle-ads-api-report-fetcher[sqlalchemy]- version with SQLalchemy supportgoogle-ads-api-report-fetcher[simulator]- version with support forsimulating
query resultsinstead of calling Google Ads API.google-ads-api-report-fetcher[full]- full versionRun the tool withgaarfcommand:gaarf<queries>[options]Documentation on available options see in the rootREADME.md.Using as a libraryOncegoogle-ads-api-report-fetcheris installed you can use it as a library.InitializeGoogleAdsApiClientto connect to Google Ads APIGoogleAdsApiClientis responsible for connecting to Google Ads API and provides several method for authentication.fromgaarf.api_clientsimportGoogleAdsApiClient# initialize from local fileclient=GoogleAdsApiClient(path_to_config="google-ads.yaml",version="v12")# initialize from remote fileclient=GoogleAdsApiClient(path_to_config="gs://<PROJECT-ID>/google-ads.yaml",version="v12")# initialize from dictionarygoogle_ads_config_dict={"developer_token":"","client_id":"","client_secret":"","refresh_token":"","client_customer_id":"","use_proto_plus":True}client=GoogleAdsApiClient(config_dict=google_ads_config_dict,version="v12")initializeAdsReportFetcherto get reportsfromgaarf.query_executorimportAdsReportFetcher,AdsQueryExecutorreport_fetcher=AdsReportFetcher(client)# create query textquery_text="SELECT campaign.id AS campaign_id FROM campaign"# Execute query and store `campaigns` variable# specify customer_ids explicitlycustomer_ids=['1','2']# or perform mcc expansion for mcc 1234567890customer_ids=report_fetcher.expand_mcc('1234567890')campaigns=report_fetcher.fetch(query_text,customer_ids)# perform mcc expansion when calling `fetch` methodcampaigns=report_fetcher.fetch(query_text,'1234567890',auto_expand=True)Use macros in your queriesparametrized_query_text="""SELECTcampaign.id AS campaign_idFROM campaignWHERE campaign.status = '{status}'"""active_campaigns=report_fetcher.fetch(parametrized_query_text,customer_ids,{"status":"ENABLED"})Define queriesThere are three ways how you can define a query:in a variablein a filein a class (useful when you have complex parametrization and validation)fromgaarf.base_queryimportBaseQueryfromgaarf.ioimportreader# 1. define query as a string an save in a variablequery_string="SELECT campaign.id FROM campaign"# 2. define path to a query file and read from it# path can be localquery_path="path/to/query.sql"# or remotequery_path="gs://PROJECT_ID/path/to/query.sql"# Instantiate readerreader_client=reader.FileReader()# And read from the pathquery=reader_client.read(query_path)# 3. define query as a classclassCampaigns(BaseQuery):def__init__(self,status:str="ENABLED"):self.query_text=f"""SELECTcampaign.idFROM campaignWHERE campaign.status ={status}"""active_campaigns=report_fetcher.fetch(Campaigns())inactive_campaigns=report_fetcher.fetch(Campaigns("INACTIVE"))Iteration and slicingAdsReportFetcher.fetchmethod returns an instance ofGaarfReportobject which you can use to perform simple iteration.query_text="""SELECTcampaign.id AS campaign_id,campaign.name AS campaign_name,metrics.clicks AS clicksFROM campaignWHERE segments.date DURING LAST_7_DAYS"""campaigns=report_fetcher.fetch(query_text,'1234567890',auto_expand=True)# iterate over each row of `campaigns` reportforrowincampaigns:# Get element as an attributeprint(row.campaign_id)# Get element as a sliceprint(row["campaign_name"])# Get element as an index (will print number of clicks)print(row[2])# Create new columnrow["new_campaign_id"]=row["campaign_id"]+1You can easily slice the report# Create new reports by selecting one or more columnscampaign_only_report=campaigns["campaign_name"]campaign_name_clicks_report=campaigns[["campaign_name","clicks"]]# Get subset of the report# Get first row onlyfirst_campaign_row=campaigns[0]# Get first ten rows from the reportfirst_10_rows_from_campaigns=campaigns[0:10]Convert reportGaarfReportcan be easily converted to common data structures:# convert `campaigns` to listcampaigns_list=campaigns.to_list()# convert `campaigns` to pandas DataFramecampaigns_df=campaigns.to_pandas()Save reportGaarfReportcan be easily saved to local or remote storage:fromgaarf.ioimportwriter# initialize CSV writercsv_writer=writer.CsvWriter(destination_folder="/tmp")# initialize BigQuery writerbq_writer=writer.BigQueryWriter(project="",dataset="",location="")# initialize SQLAlchemy writersqlalchemy_writer=writer.SqlAlchemyWriter(connection_string="")# initialize Console writerconsole_writer=writer.Console(page_size=10)# save report using one of the writerscsv_writer.write(campaigns,destination="my_file_name")bq_writer.write(campaigns,destination="my_table_name")sqlalchemy_writer.write(campaigns,destination="my_table_name")Combine fetching and saving withAdsQueryExecutorIf your job is to execute query and write it to local/remote storage you can useAdsQueryExecutorto do it easily.When reading query from fileAdsQueryExecutorwill use query file name as a name for output file/table.fromgaarf.ioimportreader,writerfromgaarf.query_executorimportAdsQueryExecutor# initialize query_executor to fetch report and store them in local/remote storagequery_executor=AdsQueryExecutor(client)# initialize writercsv_writer=writer.CsvWriter(destination_folder="/tmp")reader_client=reader.FileReader()query_text="""SELECTcampaign.id AS campaign_id,campaign.name AS campaign_name,metrics.clicks AS clicksFROM campaignWHERE segments.date DURING LAST_7_DAYS"""# execute query and save results to `/tmp/campaign.csv`query_executor.execute(query_text=query_text,query_name="campaign",customer_ids=customer_ids,write_client=csv_writer)# execute query from file and save to results to `/tmp/query.csv`query_path="path/to/query.sql"query_executor.execute(query_text=reader_client.read(query_path),query_name=query_path,customer_ids=customer_ids,write_client=csv_writer)Python specific command line flags--optimize-performance- accepts one of the following values:NONE- no optimizations are donePROTOBUF- convert Google Ads API response to protobuf before parsing
(speeds up query execution 5x times but forces conversion of ENUMs to integers instead of strings)BATCH-  converts all response of Ads API to a list and then parses its content in parallelBATCH_PROTOBUF- combinesBATCHandPROTOBUFapproaches.DisclaimerThis is not an officially supported Google product.