Google Analytics API 4: Accessing Acquisition Channels data on Python

1.1k Views Asked by At

I'm trying to write a python script to pull analytics data from the Google Analytics API. I need to know which Dimensions and or Metrics I must use to access "new users" for different types of user acquisition. Here I've enumerated the two types of acquisition methods I need to use based on the Google Analytics Web Interface:

Acquisition > All Traffic > Channels > Referral > (my specific referral site) > "New Users"

and

Acquisition > All Traffic > Channels > Social > Facebook > "New Users"

Links and code snips would be greatly helpful. Thank you!

I have referred to Google Analytics documentation here.

I cannot find the level detail required to drill down to the specific data I need. I expect outputs to be single integer numbers that match the acquisition numbers on the Analytics web interface from the same time frame.

Here is code block of a sample request I've been trying to make:

sample_request = {
  'viewId': 'XXXXXXX', 
  'dimensions': [{"name": "ga:cohort"}],
  'metrics': [{'expression': 'ga:acquisitionTrafficChannel/ga:newUsers'}],
   "cohortGroup": {
    "cohorts": [{
        "name": "cohort_1",
        "type": "FIRST_VISIT_DATE",
        "dateRange": {'startDate': datetime.strftime(datetime.now() - timedelta(days = 30),'%Y-%m-%d'),
            'endDate': datetime.strftime(datetime.now(),'%Y-%m-%d')}
        }
   ]}
}

Error:

Traceback (most recent call last):
  File "autogoogle2.py", line 90, in <module>
    'reportRequests': sample_request
  File "C:\Users\jatra\Anaconda3\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\jatra\Anaconda3\lib\site-packages\googleapiclient\http.py", line 851, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "Selected dimensions and metrics cannot be queried together.">
1

There are 1 best solutions below

0
On

I had partly the same issue. I wanted to get the channels were the visitors come from.

The "cohort" stuff didn't work for me yet. I included the dimension "ga:ChannelGrouping" which returns the default channel grouping.

However, please see my solution below, which helped me get the metrics together with the channels.

def get_report(service):
return service.reports().batchGet(
    body={
        'reportRequests': [
        {
            'viewId': 'XXXXX',
            'dateRanges': [{'startDate': '2018-08-01', 'endDate': 'today'}],
            'metrics': [{'expression': 'ga:NewUsers'}],
            'dimensions': [{'name': 'ga:Date'}, {'name': 'ga:ChannelGrouping'}],
            'pageToken': '1', #= start_index in v3
            'pageSize': '1000' #= max_results in v3
        }]
    }
).execute()