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

GA4 without client library, using ColdFusion, getting 404 error


I am working in ColdFusion, trying to convert our code to pull from GA4 instead of UA data.

I don't know how to give a minimally reproducible example, without giving security info.

My JSON looks like this: {"DATERANGES":[{"endDate":"2023-02-20","startDate":"2023-01-01"}],"METRICS":[{"name":"activeUsers"}],"DIMENSIONS":[{"name":"country"}]}

I am posting to this:

<cfhttp url="https://analyticsdata.googleapis.com/v1beta/properties/XXXXX:runReport" method="post" timeout="15">
    <cfhttpparam type="header" name="Authorization" value="Bearer #access_token#">
    <cfhttpparam type="header" name="Content-type" value="application/json">
    <cfhttpparam type="formfield" name="reportRequests" value="#jsonText#">
</cfhttp>`

To get my access_token, I am posting to https://accounts.google.com/o/oauth2/token:

<cfhttp method="post" url="https://accounts.google.com/o/oauth2/token" Result="call2data">

    <cfhttpparam type="formfield" name="refresh_token" value="#get_token.refresh_token#">
    <cfhttpparam type="formfield" name="client_id" value="#oauth_client_id#">
    <cfhttpparam type="formfield" name="client_secret" value="#oauth_client_secret#">
    <cfhttpparam type="formfield" name="grant_type" value="refresh_token">

</cfhttp>

I have tested the code to refresh my access_token, and I do get a new access_token everytime, so that code is working.

When I post this code, I get back a 404 error, with this message: "The requested URL /v1beta/properties/XXXXXXX%3ArunReport was not found on this server. That’s all we know."

If I put "123456" in as the access_token in the header, I also get back that same error, so it does seem that the POST is failing on the URL, not on Authorization.

The code DOES work when posting to the API Explorer at https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport If I enter properties/XXXXXX as the property and

{
  "metrics": [
    {
      "name": "activeUsers"
    }
  ],
  "dimensions": [
    {
      "name": "country"
    }
  ],
  "dateRanges": [
    {
      "startDate": "2023-01-01",
      "endDate": "2023-02-20"
    }
  ]
}

as the request body, I get correct results returned.

However, the API explorer POSTs to https://content-analyticsdata.googleapis.com/v1beta/properties/XXXXXX:runReport?alt=json I tried POSTing to that URL, but got the same error message.

I assume that I am missing something blindingly obvious?? Any ideas, suggestions, war stories would be greatly appreciated. Of course if anyone has an example of accessing GA4 without a client library, that would be awesome.


Solution

  • I had this problem, it is because of the colon in the URL.

    cfhttp automatically changes :runReport to %3ArunReport which causes a 404.

    If you are using Lucee, you can stop this behaviour with the encodeUrl="false" parameter.