Google Analytics Query Explorer doesn't match api results - google-analytics

I have the following request:
viewId: XXXXXX,
dateRanges: [ { startDate: '7daysAgo', endDate: 'today' } ],
metrics: [{expression: 'ga:sessions'}, {expression: 'ga:avgSessionDuration'}],
dimensions: [{name: 'ga:date'}, {name: 'ga:country'}, {name: 'ga:source'}, {name: 'ga:countryIsoCode'}, {name: 'ga:pagePath'}],
samplingLevel: 'LARGE'
When I run this query on the GA Query Explorer I get the data returned exactly how I want it.
When I do an API request, I am only returned the rows where sessions > 0.
I think the Query Explorer is still running V3 of the API. But am I missing something obvious?
Here is the response from the Query Explorer. The red section is what is returned when I do the exact same call via a Node Request:

After a little more research I found the following in the Google Analytics API v3 to v4 migration docs:
The v3 include-empty-rows parameter corresponds to the includeEmptyRows field in v4. The v3 parameter defaults to true, while in v4 the field defaults to false. If you do not have the value set in v3 you will need to set the value to true in v4.
Since the Query Explorer is using v3, this is why you see the discrepancy.

Related

How to filter the HERE API V7 reversegeocode api to by resulttype?

I am applying the migration of HERE geocoder API from v6 to v7.
My requirement is to fetch the available cities around the selected address by radius.
In v6 I have achieved this by using the below object:
geocoder.reverseGeocode(
{
level: 'city',
mode: 'retrieveAreas',
prox: '36.7783,119.4179,1000',
gen: 9,
maxresults: 50,
jsonattributes: 1,
},
onSuccessFetchCity,
onError
)
In v7 after reading the migration document I have changed the object like below:
platform.getSearchService().reverseGeocode(
{
level: 'city',
mode: 'retrieveAreas',
in: 'circle:36.7783,119.4179;r=1000',
gen: 9,
limit: 50,
jsonattributes: 1,
},
onSuccessFetchCity,
console.error
)
but level: city is not working, currently, I am getting all types of addresses into result.
Can anyone help me out on this?
Please note HERE geocoder API v7 is yet to release officially in China Specific regions. Only beta version is now available for use.
For more information kindly refer https://developer.here.com/cn/documentation/geocoder/topics/includes.html

Google Analytics server side call err "The value provided for parameter 'tid' is invalid. using a valid" with measurement ID

I am trying to do a server side call to Google Analytics 4 with a valid Measurement ID (G-0GHN4RGNDQ) it's a test one, so OK to share here, see https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#v and the debug call here:
https://www.google-analytics.com/debug/collect?v=1&tid=G-0GHN4RGNDQ&cid=555&t=event&ec=MyCategory&ea=MyAction&el=MyLabel
I get this error
{
"hitParsingResult": [ {
"valid": false,
"parserMessage": [ {
"messageType": "ERROR",
"description": "The value provided for parameter 'tid' is invalid. Please see https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters for details.",
"messageCode": "VALUE_INVALID",
"parameter": "tid"
} ],
"hit": "/debug/collect?v=1\u0026tid=G-0GHN4RGNDQ\u0026cid=555\u0026t=event\u0026ec=MyCategory\u0026ea=MyAction\u0026el=MyLabel"
} ],
"parserMessage": [ {
"messageType": "INFO",
"description": "Found 1 hit in the request."
} ]
I can successfully make gtag calls using that same Measurement ID and the events show up in Google Analytics... however I can't seem to get it to work via the /debug/ url above.
Any help appreciated.
You appear to be using the endpoint for
Measurement Protocol (Universal Analytics)
https://www.google-analytics.com/debug/collect?tid=fake&v=1
However yet you state you are trying to use Google Analytics 4 which implies GA4 and not Universal analytics.
You should be using Measurement Protocol (Google Analytics 4)
POST /mp/collect HTTP/1.1
HOST: www.google-analytics.com
Content-Type: application/json
<payload_data>
For validating hits check this page page
Note:
Remember the measurement protocol is used to send Data TO Google Analytics not request data from google analytics.

Missing some rows for a ga:source when requesting custom dimension "userType" on Reporting API v4

I am using the Analytics Reporting API v4 to get a report with this body:
{
'viewId': XXX,
'dateRanges': {
'startDate': "2021-03-16",
'endDate': "2021-04-14"
},
'metrics': [
"ga:itemQuantity", "ga:itemRevenue"
],
'samplingLevel': 'LARGE',
'pageSize': 100000,
'hideTotals': False,
'dimensions': ["ga:source", "ga:date", "ga:dimension4"]
}
If I compare the total itemRevenue with what I have on Analytics interface in the "Product performance" report, I have the same results for the whole period but if I check on a subperiod I have some different numbers.
I did the same test with a start_date="2021-04-09" and end_date="2021-04-15" and this time I always have different results. The missing rows always match ga:source=affiliation.
If I remove the ga:dimension4 (corresponding to userType in the interface), my results are always the same.
Could someone explain why my results are not consistent between the API and the interface?

Google Analytics User-ID report Dimensions and Metrics

I need to populate my database with the User-ID report data for each user (The report I am referring to can be found in Google Analytics > Reports > User Explorer (> click on the user id)).
I am looking at the documentation, but cannot seem to find any dimensions or metrics that I can use to accomplish this: https://ga-dev-tools.appspot.com/dimensions-metrics-explorer/?authuser=1
I wish I had some code examples, however the alternative method would be to run this script (with all the other functions that I will not include in here for simplicity):
def get_user_Activity(analytics, VIEW_ID, user_id, start_date, end_date):
# Use the Analytics Service Object to query the Analytics Reporting API V4.
return analytics.userActivity().search(
body={
"viewId": VIEW_ID,
"user": {
"type": "USER_ID",
"userId": user_id
},
"dateRange": {
"startDate": start_date,
"endDate": end_date
},
"activityTypes": [
"PAGEVIEW", "EVENT"
]
}
).execute()
Which will yield this dictionary for each user-id:
{'sessions': [{'sessionId': '1579xxxx',
'deviceCategory': 'desktop',
'platform': 'Windows',
'dataSource': 'web',
'activiti es': [{'activityTime': '2020-01-22T12:48:20.971410Z',
source': '(direct)',
'medium': '(none)',
'channelGrouping': 'Direct',
'campaign': '(not set)',
'keyword': '(not set)',
'hostname': 'example.com',
'landingPagePath': '/somelandingpage',
'activityType': 'PAGEVIEW',
'customDimension': [{'index': 1}],
'pageview': {'pagePath': '/some/page', 'pageTitle': 'SOME Title'}},
{'activityTime': '2020-01-22T12:48:20.970754Z',
'source': '(direct)',
'medium': '(none)',
'channelGrouping': 'Direct',
'campaign': '(not set)',
'keyword': '(not set)',
'hostname': 'example.com',
'landingPagePath': '/somelandingpage',
'activityType': 'PAGEVIEW',
'customDimension': [{'index': 1}],
'pageview': {'pagePath': '/some/other/path', 'pageTitle': 'SomeTitle'}},...
..................
etc ..............
The trouble of this method is that I would have to go calculate most of the metrics that I am interested in, instead, I would prefer to merely collect the metrics and populate the DB.
If the needed "ga:dimension(s)" and "ga:metric(s)" could please be provided, it would be highly appreciated.
There's no built-in support for userId-level reporting in Google Core Reporting API, so you'll have to calculate all the necessary metrics on your side based on what's available in the Activity API responses.
The only alternative is having a user-level custom dimension with the same value as user ID. However, this only works if you have this tracking implemented in advance.

Google Analytics API - Get page view information for specific URLs

I am looking to implement a page view tracking system on one of my websites.
The website is a directory where suppliers can advertise their services. Suppliers have a unique profile page on the site, e.g mysite.com/directory/abc-profile.html
The idea is that suppliers can log in to their account area on the site and view stats on how many people are visiting their profile. Ideally I want to display this as :
Total views | Total today | This week | This month | This year
It does not matter if the data is not completely up to date.
I already have Google Analytics tracking code installed on the site. Is it possible to use the Google Analytics API to retrieve this data? If so, what kind of query do I need to make? I had a look on the documentation but could not figure whether the functions allow this or not.
I am using PHP and MySQL on the server.
Yes - you will need to use the Google Analytics API for this. I would suggest checking out the Query Explorer to get a feel for the queries you will need to create.
You will require numerous queries to get all the data you need (adjusting the starting date):
- Total Views
- This Year
- This Month
- This Week (i.e. last 7 days - from which you could also get Total Today).
Here is an example query:
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:1234456789&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath==/about-us.html&start-date=2013-10-15&end-date=2013-10-29&max-results=50
Alternatively, you might want to consider www.embeddedanalytics.com (disclosure - I work with them). We have a service/platform that allows website owners to embed GA based charts/statistics without having to learn the GA API. We have a CMS version which will do exactly what you need (where you script the call to pass the page path). We have done something like this with a number of podcast sharing sites.
Google suggests using Reporting API V4 now. The accepted answer uses V3.
Here is a V4 request example:
POST https://analyticsreporting.googleapis.com/v4/reports:batchGet?key={YOUR_API_KEY}
{
"reportRequests": [
{
"viewId": "YOUR_VIEW_ID",
"dimensions": [
{
"name": "ga:pagePath"
}
],
"metrics": [
{
"expression": "ga:pageviews"
}
],
"dimensionFilterClauses": [
{
"filters": [
{
"operator": "EXACT",
"dimensionName": "ga:pagePath",
"expressions": [
"/your-path"
]
}
]
}
],
"dateRanges": [
{
"startDate": "2009-12-31",
"endDate": "2016-09-28"
}
]
}
]
}
where
YOUR_API_KEY - for auth related things follow this page
YOUR_VIEW_ID - you can use the Account Explorer to find a View ID. (or Admin -> View -> View Settings -> View ID).
For more documentation details and a "Try it!" console follow this page.
You should be able to add a filter on the landing page. I am assuming that each user's site has its own start page. This returns only the data for that user. If you want the code on how to do this I suggest you google: Google analytics core reporting API PHP tutorial
Another idea would be to let the user add there Google Analytics account to there profile. Then you can output the google analytics code onto there page. Then they can track there own google analytics data and you won't need to deal with any of it.
Thought I would provide an updated version as the others are showing for V3 and V4 - for anyone using the latest API for Google Analytics Data API (GA4). This is just grabbing the total users, over a date range for a specific path.
Note that the POST is hitting the v1 beta address as this was the latest at the time.
POST https://analyticsdata.googleapis.com/v1beta/properties/PROPERTY_ID:runReport
{
"dateRanges": [
{
"startDate": "YYYY-MM-DD",
"endDate": "YYYY-MM-DD"
}
],
"dimensions": [
{
"name": "pagePath"
}
],
"dimensionFilter": {
"filter": {
"fieldName": "pagePath",
"stringFilter": {
"matchType": "CONTAINS",
"value": "/YOUR/PATH"
}
}
},
"metrics": [
{
"name": "totalUsers"
}
]
}

Resources