Search code examples
google-analytics-apigoogle-analytics-4

GA4 (Google Analytics) sessions based on UTM params


I am trying to fetch sessions from GA4 which are relevant to specific UTM params.

In GA3 we were able to use segments (sessions::condition::ga:source==X;ga:medium==Y) but I can not find a way to do this on GA4.

POST https://analyticsdata.googleapis.com/v1beta/#{property}:runReport`

Payload like this:

body = {
  "metrics": [
    {
      "name": "sessions::condition::ga:source==X;ga:medium==Y"
    }
  ], 
  "dimensions": [
    {
      "name": "date" 
    }
  ],
  "dateRanges": [
    {
      "startDate": '2022-01-01',
      "endDate": '2022-01-30',
      "name": "current_year"
    }
  ]
}

Returns: Field sessions::condition::ga:source==X;ga:medium==Y is not a valid metric.. Is there a way to do this via new API?

Should I use dimension filter to achieve that? I need to query on both source&medium but it is not clear how do I do this?

  "dimensionFilter": {
      "filter": {
        "fieldName": "firstUserMedium",
        "stringFilter": {
          "value": "Y"
        }
      }
    }

Solution

  • A dimension filter on sessionSource & sessionMedium returns sessions that have those specific utm_source & utm_medium values. See the dimensions & metrics page for a description of these and other dimensions & metrics.

    The needed dimension filter is similar to the following. See Dimension Filters in Creating a Report for more info.

    "dimensionFilter": {
      "andGroup": {
        "expressions": [
          {
            "filter": {
              "fieldName": "sessionSource",
              "stringFilter": {
                "value": "X"
              }
            }
          },
          {
            "filter": {
              "fieldName": "sessionMedium",
              "stringFilter": {
                "value": "Y"
              }
            }
          }
        ]
      }
    },
    

    Segments are not yet available today in the GA4 Data API.