google analytics demographics intrest overview fetch - google-analytics

I want to get all the data from google analytics. Can you please explain how to get data of "isitors-demographics-interest-overview"
Affinity Category
In-Market Segmen
Other Category0.00% of total users
I used some codes to get data from google analatics but i am stuck on "intrest menu"
$age = Analytics::performQuery($pobj, 'data', ['metrics' => 'ga:users','dimensions' => 'ga:userAgeBracket']);
$google['age'] = $age;
/*gender*/
$gender = Analytics::performQuery($pobj, 'data', ['metrics' => 'ga:users','dimensions' => 'ga:userGender']);
$google['gender'] = $gender;

The google analytics API is not related to the Google analytics website. The google analytics website has set up reports that have been processed internally.
you can not get ALL your google analytics data unless you have a premium account in that case you can request that it be exported to BigQuery.
You can not get the interest menu report directly. Your going to have to build up the data yourself using the dimensions and metrics available

Related

Different Results In Exporting Data From Google Analytics 4

I have tried using Google Analytics Data Api - and issue with it is that the numbers don't much up with what I get from api and from what I see on web ui of Google Analytics. I even tried query explorer for Google Analytics Data Api but got less results again.
From what I am assuming and come to know that google sampling applies on GA Data Api (Although I have results of a day in few hundreds only). Now I heard there is no option to control sampling in GA Data API but there was in GA Reporting API by controlling sampling size option. So I decided to use that. But to my surprise Reporting API only takes View ID and I only had Property ID because I was using GA4 (can't enable universal analytics).
This takes me down to what? I tried Management api and it is for controlling options but not to view data. I tried to import data into Looker and exported from there to myself. But Looker has same results I get from query explorer which are less than web ui of Google Analytics.
I want to do this programatically so just can't use manual export option of GA4.
Need help in finding best way to do it !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
I have done this same thing in google analytics data api, query explorer as well as ga web ui. Ga web ui shows the most results. While query explorer and google analytics data api shows the same after sampling. Attached screenshots for reference.
GA WEB UI _ QUERY
GA WEB UI _ RESULTS EXPORTED TO CSV
QUERY EXPLORER_ QUERY
QUERY EXPLORER_ RESULTS
GA4 DATA API_ RESULTS
EVEN TRIED 3rd PARTY SERVICE Supermetrics GOT SAME
Here is code for GAT DATA API:
`
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
from collections import defaultdict
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = 'MY_GA.json'
property_id = 'properties/266233569'
dimensions = ["date","platform","customEvent:order_id"]
metrics = ['sessions']
request = {
"requests": [
{
"dateRanges": [
{
"startDate": "2022-10-19",
"endDate": "2022-10-19"
}
],
"dimensions": [{'name': name} for name in dimensions],
"metrics": [{'name': name} for name in metrics],
"limit": 10000,
"return_property_quota": True,
"keep_empty_rows": True
}
]
}
credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsdata', 'v1beta',
credentials=credentials)
response =
analytics.properties().batchRunReports(property=property_id,
body=request).execute()
`
I believe it's a GA4 limitation. If you're considering third-party solutions, Able CDP has its own tracking that connects to BigQuery (so easily accessible in Looker) and provides raw tracking data without sampling.

Google Analytics UserID API extraction

Trying to extract a userID from GoogleAnalytics. This is to view which user is the using the website most and least.
I would to retrieve the top 5 user IDs and bottom 5 user IDs that were passed using either:
gtag('config', 'GA_TRACKING_ID', {
'user_id': 'USER_ID'
});
OR
using a custom dimension... ( https://support.google.com/analytics/answer/2709828?hl=en )
I'm (vaguely) aware of policies and TOS to keep 'non identifying' information on Google BUT there are posts online indicating you can link back to CMS data.
Steps so far
Google Analytics with UserID and view setup - Working in Google dashboard and showing filtered userID and All website data using the idea.
Requirements:
Extract page view and session data for each userId between a date
range (or all by default)
UserID via standard GA method
UserID via Custom dimension method
Any help, pointers or examples how someone has completed something like this are appreciated.
NOTE: This is to PULL data out of GA and manipulate/display it on an external system/dashboard.
Seen this which states it's not possible: Google analytics userID tracking
and this which states it (kind of) is google analytics API implementation for tracking a specific user activities in php
The solution I used:
Tracking
Create Google Analytics account
Create a new view by activating the UserID tracking (labeled NewView1)
Use https://developers.google.com/analytics/devguides/collection/gtagjs/custom-dims-mets
i.e. Define your custom dimension
Get Analytics tracking code + Add custom definition code
Create a Custom report using the 'metrics' you want to see and filtering by the 'custom dimension' I created earlier.
(note: data took ~ 12 hours to be visible so don't expect to work instantly)
Front end tracking additions
gtag('config', 'GA_TRACKING_ID', {
'custom_map': {'dimension<Index>': 'dimension_name'}
});
// Sends the custom dimension to Google Analytics.
gtag('event', 'any_event_name', {'dimension_name': dimension_value});
Extraction
Create New Google Developer Console Project (API)
Use a Service Account to connect the API with Analytics ( https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php ) -- API -> credentials -> Create Credentials (Service Account key)
(assign role [mine was set to Project => View])
Save the Text file to your filesystem and rename to json as per examples
Add permissions to your Analytics project by copy/pasting the 'Email' from the Service account details into Analytics User Management.
Get the view ID of the data you wish to extract (Analtyics created in step 2 in tracking)
Use the sample Code (HelloAnalytics.php) to connect and extract data
Use your custom dimension to filter results
The dimension filter I used was $dimensions (see below)
...
$dimensions = new \Google_Service_AnalyticsReporting_Dimension();
$dimensions->setName('ga:dimension1'); // as per docs
// Create the ReportRequest object.
$request = new \Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions, $pageviews));
$request->setDimensions($dimensions);
From there I was able to see the same data via API that I could see in the custom report on analytics web.
NOTE: be careful of which Google project and view you're in while setting up
permissions and dimensions.
NOTE: using gtag() code and not Universal (ga()) js code
The answer is a very brief/rough summary of how I achieved my specific goal. It is not a one-size-fits all solution but hopefully it will give someone a better idea of how to set and extract custom variable data within Google.
The final result was data from the API. From there it's up to you.

Google Analytics API data mismatch

I set up a custom variables to get data from Google Analytics and store into a local database.
Requirement : I want to get a list of the users,sessions,event label,total events,unique events,event value,operating system,browser and device category.
Problem :
I've checked the dashboard on Google Analytics, and the data is being reported fine. However, I noticed that on the Google Analytics, the data listed in the column unique events don't match the amounts I get when requesting the Google Analytics API.
Data shows by GA :
Data shows by GA API :
Query that i am using in GA API :
public function getEventsLabelByDate($params=array()) {
$defaults = array(
'metrics' => 'ga:visitors,ga:visits,ga:totalEvents,ga:uniqueEvents,ga:eventValue',
'dimensions' => 'ga:eventLabel,ga:eventCategory,ga:country,ga:operatingSystem,ga:browser,ga:date,ga:deviceCategory',
'filters' => 'ga:eventAction==Play Done',
);
$_params = array_merge($defaults, $params);
return $this->_query($_params);
}
$data = $ga->getEventsLabelByDate();
I want to know what's best to use in my API calls. Any immediate help will be highly appreciable. Thanks.
I encountered the same issue.
My workaround was to change the dimensions to ga:eventCategory and then summed up the returned uniqueEvents. That provided a number identical to the uniqueEvent per eventAction on the web interface.
Using more granular dimensions resulted in an accurate number. Hope that works for you too.

Why data i get from google analytics API not match with google analytics web interface?

I used Google API to get data from google analytics, but the metrics not the same with the web interface of google analytics.
ie: I get data on 2015-03-01 - It return pageviews 79
But on web interface of google analytics, it is 80.
I had searched on some question the same me, but almost them show the way to solve is Sampling level.
I tried to set other Sampling level
DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
if (dimensions != null)
{
request.Dimensions = string.Join(",", dimensions);
}
request.SamplingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.HIGHERPRECISION;
request.StartIndex = startIndex;
return request;
after that, the result return the same before, it not change.
So, anyone know this issue?
Simple its sampled data vs. unsampled data which you can read about here: https://support.google.com/analytics/answer/1042498?hl=en
For API work i normally use a web query explorer to verify that my API call's are being sent and responses match to verify the data: https://ga-dev-tools.appspot.com/explorer/

How to get data from Google analytics api for different websites

Google analytics api for different websites for example:
I have 67 websites and there record in Google analytics.
Actually I want single website Top 10 links most visited, with numbers of times that link is visited and total website visits and search engine visits.
I have used GAPI but it doesn't show for specific website :
$ga = new gapi('xxxxx#gmail.com', 'xxxxxxx');
$dimensions = array('browser','source','region');
$metrics = array('pageViews','visitors','visits');
$ga->requestReportData('12312123', $dimensions, $metrics, '-visits');
$gaResults = $ga->getResults();
if you have answer for Google analytics with zend framework2,you can answer for this Question
I Found Solution My Own:
Account detail that cantain you websites:
$ga = new gapi('xxxxx#gmail.com', 'xxxxxxx');
give dimension and metrics that you want from google analytic
$dimensions = array('browser','source','region');
$metrics = array('pageViews','visitors','visits');
Each website in google analytics have a profile_id:123456
You can see it by login in to your account.
$ga->requestReportData(profile_id, $dimensions, $metrics, '-visits');
you will retrive data for specific website

Resources