Noque
Noque

Reputation: 373

Direct Traffic Filter in Google Analytics

I would like to filter by Direct Traffic users. In the API it suggests it as a 'segment' value. Where could is add it in the following code?

In y_metric I have 'ga:sessions'

https://developers.google.com/analytics/devguides/reporting/core/v4/samples#multiple_segments

def get_report(analytics, start_date_time, end_date_time, y_metric, VIEW_ID):
    """Queries the Analytics Reporting API V4.
       Args:
     analytics: An authorized Analytics Reporting API V4 service object.
     Returns:
     The Analytics Reporting API V4 response.
    """
    return analytics.reports().batchGet(
        body={
            'reportRequests': [
                {
                    'viewId': VIEW_ID,
                    'dateRanges': [{'startDate': start_date_time, 'endDate': end_date_time}],
                    'metrics': [{'expression': y_metric}],
                    'segments'
                    'dimensions': [{'name':'ga:date'},{'name':'ga:year'}, {'name':'ga:month'}, {'name':'ga:hour'},{'name':'ga:day'},
                               {'name':'ga:minute'}, {'name':'ga:deviceCategory'}],
                    # "pageToken": "21000",
                    "pageSize": "1000"
                }]
        }
    ).execute()

Upvotes: 0

Views: 208

Answers (1)

Noque
Noque

Reputation: 373

The solution is including the following in the body as follows:

                    'dimensions': [{"name": "ga:segment"} , {'name':'ga:date'},{'name':'ga:year'}, {'name':'ga:month'}, {'name':'ga:hour'},{'name':'ga:day'},{'name':'ga:minute'}, {'name':'ga:deviceCategory'}],
                "segments":[{"segmentId": ''gaid::-7'' }],

For a complete reference on the static segments to be retrieved:

'''
gaid::-1 All Visits
gaid::-2 New Visitors
gaid::-3 Returning Visitors
gaid::-4 Paid Search Traffic
gaid::-5 Non-paid Search Traffic
gaid::-6 Search Traffic
gaid::-7 Direct Traffic
gaid::-8 Referral Traffic
gaid::-9 Visits with Conversions
gaid::-10 Visits with Transactions
gaid::-11 Mobile Traffic
gaid::-12 Non-bounce Visits
'''

Upvotes: 1

Related Questions