2

I followed the Google Analytics (GA) Hello Analytics tutorial and used the query explorer to call the GA API via Python and this worked great until I tried to include a segment in my query. It seems that the query explorer's use of segments (or my understanding of how to use this) is not correct. Here is my get_report function:

def get_report(analytics, segment):
if segment == "all":
    bdy = {
        'reportRequests': [
            {
                'viewId': VIEW_ID,
                'dateRanges': [{'startDate': '2021-01-19', 'endDate': 'yesterday'}],
                'metrics': [{'expression': 'ga:uniqueEvents'}],
                'dimensions': [{'name': 'ga:eventLabel'}]
            }]
    }
elif segment == "internal":
    bdy = {
        'reportRequests': [
            {
                'viewId': VIEW_ID,
                'dateRanges': [{'startDate': '2021-01-19', 'endDate': 'yesterday'}],
                'metrics': [{'expression': 'ga:uniqueEvents'}],
                'dimensions': [{'name': 'ga:eventLabel'}],
                "segment": "gaid::aqYF4QvFTX6JhLKfs0R84A"
            }]
    }

return analytics.reports().batchGet(body=bdy).execute()

The first if block works perfectly fine but when I try to run the second I get this error:

HttpError: <HttpError 400 when requesting https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "Invalid JSON payload received. Unknown name "segment" at 'report_requests[0]': Cannot find field.". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'report_requests[0]', 'description': 'Invalid JSON payload received. Unknown name "ga:segment" at 'report_requests[0]': Cannot find field.'}]}]">

It seems like the "segment" key in the second body dictionary is not correct, but I can't find what it should be. Does anyone know how to correct this?

In case this is helpful, this is what the query explorer suggested I use:

"query": {
"start-date": "2021-01-19",
"end-date": "yesterday",
"ids": "ga:xxxxxxxx",
"dimensions": "ga:eventCategory,ga:eventLabel",
"metrics": [
  "ga:uniqueEvents"
],
"segment": "gaid::aqYF4QvFTX6JhLKfs0R84A",
"start-index": 1,
"max-results": 1000

}

I think the query explorer might use v3 of the API, while I'm using v4....

Thanks in advance!

1 Answer 1

1

Try

 "segments":[
    {
      "segmentId": "gaid::aqYF4QvFTX6JhLKfs0R84A"
    }]

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that's it. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.