I'm trying to measure the API calls made via my server and instead of storing the API usage in my server I'm pushing it to GA4 using Measurement Protocol. I've successfully implemented it and am pushing events successfully using this code:
$eventData = [
'appInstanceId' => $appInstanceId,
'userId' => $userId,
'events' => [
'name' => 'api_request',
'params' => []
]
];
$firebaseAppId = Settings::get('firebase_app_id');
$appSecret = Settings::get('firebase_api_secret');
$out = Http::get(sprintf('https://www.google-analytics.com/mp/collect?firebase_app_id=%s&api_secret=%s', $firebaseAppId, $appSecret), function ($http) use ($eventData) {
$http->setOption(CURLOPT_POSTFIELDS, json_encode($eventData));
});
Which is basically a PHP adaptation of this code.
And it successfully pushes the event to firebase and I can even view it on the firebase analytics console. However, when I try to fetch the same using the GA4 data API, it fails. I tried to manually create the metric from the Google Analytics dashboard "Custom Definitions" tab's and it appeared in the meta API and it showed under the metrics array. However, when I fetch the data it fails.
I was experimenting a bit and tried renaming the field to api_request_2 and used the same code. This time when I went to the custom definitions section, it auto-created the field except as a "dimension". I was confused and so I tried doing a fetch of the same using runReport API, except this time using it as a dimension, and the metric as eventCount. That actually worked and returned a result. But this isn't useful for me because I need it as a metric so I can put it on a graph against it's dimension (Date) so I have a count of the APIs requests on a per-day basis. How do I go about making this work?