YOGESH
YOGESH

Reputation: 63

Google analytics fetch user id in reporting API

I like to fetch user id which is available in user explorer report google analytics. I am using below batchGet to get the list of user ids using ga:clientId https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet

I am able to get the client ids, but when trying the same id with below API https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/userActivity/search#request-body

Its returning 400 error not found. Even if I copy the user id which is visible in user explorer reporting dashboard in google analytics it still return 400 error not found. Is there anything I am doing wrong?

Code snippet

analytics = build('analyticsreporting', 'v4', credentials=credentials)
body={
              "viewId": VIEW_ID,
               "user": {
                 "type": "USER_ID", # I have tried CLIENT_ID Also
                 "userId": user_id # For now I have copied the value directly from the user explorer from browser itself for testing.But it didn't worked
              }
      }
 result=analytics.userActivity().search(body=body).execute()

Response

Traceback (most recent call last): File "ga_session_data.py", line 192, in ga.main() File "ga_session_data.py", line 178, in main result=analytics.userActivity().search(body=body).execute() File "env/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper return wrapped(*args, **kwargs) File "env/lib/python3.6/site-packages/googleapiclient/http.py", line 856, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: https://analyticsreporting.googleapis.com/v4/userActivity:search?alt=json returned "CLIENT_ID: XXXXXXXX not found.">

Upvotes: 2

Views: 2797

Answers (2)

Salman Malik
Salman Malik

Reputation: 1118

This is a weird bug in Google Analytics' Reporting API. I stumbled upon the same problem and have figured out what is wrong here. When fetching a user recently recorded in Google Analytics, you can't simply query it with User ID because somehow google tries to fetch results from the previous week.

Why Not Found?

The response from GA Reporting API is half the story, when the GA Reporting API says USER_ID: {xxx-yyy-zzz} not found it never means that user is never recorded by GA, Instead what it means is that The User you requested data for is not found in this date range

Solution

Make use of date while fetching users this way you are safe from USER_ID: {xxx-yyy-zzz} not found error.

Via Analytics Reporting API

https://analyticsreporting.googleapis.com/v4/userActivity:search:

{
  "user": {
    "type": "USER_ID",
    "userId": "your-custom-user-id"
  },
  "viewId": "XXXXYYYY",
  "dateRange": {
    "startDate": "2022-11-12",
    "endDate": "2022-11-16"
  }
}

via Hello Analytics (PHP):

composer require google/apiclient:^2.0
    $client = new Client();
    $client->setAuthConfig(storage_path('app/analytics/service-account-credentials.json'));
    $client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);

    // Create the DateRange object.
    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("7daysAgo");
    $dateRange->setEndDate("today");

    $analytics = new Google_Service_AnalyticsReporting($client);

    $user = new Google_Service_AnalyticsReporting_User();
    $user->setType("USER_ID"); // pass "CLIENT_ID" for using Client ID
    $user->setUserId("your-custom-user-id"); //User ID

    $userActivityRequest = new Google_Service_AnalyticsReporting_SearchUserActivityRequest();
    $userActivityRequest->setViewId(env('ANALYTICS_VIEW_ID'));
    $userActivityRequest->setDateRange($dateRange);
    $userActivityRequest->setUser($user);

    // Passing params is optional
    $param = [
       
    ];

    $sessions = $analytics->userActivity->search($userActivityRequest, $param);

More info regarding this method can be found here

More Ways

*Please Consider suggesting edits to improve this answer.

Upvotes: 0

Дмитро Булах
Дмитро Булах

Reputation: 3847

User ID and client ID are two distinct dimensions in Google Analytics. User explorer report is based on user ID and this id might differ from client Id that appears in API report under ga:clientId dimension. To use Activity reports based on client Id value, use the following object in your Activity request:

{
  "type": "CLIENT_ID",
  "userId": "your.value"
}

In order to get data for particular User ID that appears User explorer report use the following object:

{
  "type": "USER_ID",
  "userId": "your.value"
}

https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/userActivity/search#request-body

Upvotes: 2

Related Questions