knagode
knagode

Reputation: 6125

Read GA4 (Google Analytics 4) sessions via API

Our app has access & refresh token for our customers and we have permissions to read their Google analytics accounts. We noticed that we can not access data of GA4 properties.

I managed to list GA4 properties:

GET https://analyticsadmin.googleapis.com/v1alpha/accountSummaries
headers: Authorization: Bearer @TOKEN

However I can not find a way to retrieve e.g. sessions in last 30 days for GA4 properties (which are returned in the response above). It seems like something like request below should do the trick:

POST https://analyticsdata.googleapis.com/v1beta/{property=properties/*}:runReport
headers: Authorization: Bearer @TOKEN

But it doesn't work. What am I missing? Even hints would be welcome!

Upvotes: 2

Views: 2595

Answers (1)

Brett
Brett

Reputation: 1289

You need to specify the metrics and dateRanges in the body of the POST request to :runReport method. This is an example HTTP Post Report Request & Response. This API Quickstart Guide discusses specifying the request body in a request.json, enabling the Data API, & configuring authentication.

For this report, your request should be similar to the following. GA4_PROPERTY_ID should be replaced with your numeric Google Analytics 4 Property ID.

POST https://analyticsdata.googleapis.com/v1beta/properties/GA4_PROPERTY_ID:runReport
  {
    "dateRanges": [{ "startDate": "29daysAgo", "endDate": "today" }],
    "metrics": [{ "name": "sessions" }]
  }

For this report, the response will be similar to the following:

{
  "metricHeaders": [
    {
      "name": "sessions",
      "type": "TYPE_INTEGER"
    }
  ],
  "rows": [
    {
      "metricValues": [
        {
          "value": "1495"
        }
      ]
    }
  ],
  "rowCount": 1,
  "metadata": {
    "currencyCode": "USD",
    "timeZone": "America/Los_Angeles"
  },
  "kind": "analyticsData#runReport"
}

Upvotes: 1

Related Questions