I am working on an application that in which I need to integrate google analytics API with PHP.
Here's the link for the API documentation Google Analytics Core Reporting API, currently I'm facing an overload issue.
At our application we need to form a graph for selected daterange. For example session count. API has option for parameters like start & end data but in response it only provides average / total of session counts / page load time. But for generating graph we do need data of each day in the given date range. e.g. 1 jan to 30th jan of 2015, for this case we have to send 30 requests for individual day & get the data for the graph with this method. Is there any possible way in which we can reduce request count or get data in date format?
We are collecting many metrics like Average page load time, Organic Sessions etc. which is making it 180-210 request on page load to google API itself & sometimes it throws an error that too much utilization of resources from google.
You can add the ga:date dimension. It will break out the value for each metric for every date within the date range:
In JSON
{
"reportRequests":
[
{
"dimensions":
[
{
"name": "ga:date"
}
],
"metrics":
[
{
"expression": "ga:sessions"
},
{
"expression": "ga:avgpageloadtime"
}
],
"viewId": "XXXX",
"dateRanges":
[
{
"startDate": "7daysAgo",
"endDate": "yesterday"
}
]
}
]
}
In PHP
// Create the DateRange object.
$dateRange = new Google_Service_Analyticsreporting_DateRange();
$dateRange->setStartDate("7DaysAgo");
$dateRange->setEndDate("yesterday");
// Create the Metrics objects.
$sessions = new Google_Service_Analyticsreporting_Metric();
$sessions->setExpression("ga:sessions");
$avgpageloadtime = new Google_Service_Analyticsreporting_Metric();
$avgpageloadtime->setExpression("ga:avgpageloadtime");
//Create the Dimensions object.
$date = new Google_Service_Analyticsreporting_Dimension();
$date->setName("ga:date");
// Create the ReportRequest object.
$request = new Google_Service_Analyticsreporting_ReportRequest();
$request->setViewId("XXXX");
$request->setDateRanges($dateRange);
$request->setDimensions(array($date));
$request->setMetrics(array($sessions, $avgpageloadtime));
$body = new Google_Service_Analyticsreporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analyticsreporting->reports->batchGet( $body );
Related
I am setting up a reporting script which gets data from google analytics .I am adding three dimensions to get the data but one of the those dimensions is custom dimension named test_dimension. When i set this dimension i get this error.
Unknown dimension(s): test_dimension
I tried the developer API but cannot get the expected results
https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=custom_variables_or_columns&jump=ga_dimensionxx
$custom = new Google_Service_AnalyticsReporting_Dimension();
$custom->setName("test_dimension");
$campaign = new Google_Service_AnalyticsReporting_Dimension();
$campaign->setName("ga:campaign");
$sourceMedium = new Google_Service_AnalyticsReporting_Dimension();
$sourceMedium->setName("ga:sourceMedium");
$request->setDimensions(array($custom,$campaign,$sourceMedium));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
I expect the output with the applied dimensions. If i remove the custom dimension the code works.
You'll need to use the index of the custom dimension (e.g. ga:dimension03) instead of its name. The index is visible in the property's admin settings under Custom Definitions.
I'm trying to automatise the Google analytics report of our app websites, something like 55 or so.
What I need is:
avg time
users new/returning
direct/referral/search
users per day (based on 1st of the month to the last day)
I'm using the guide from Google
https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-php
my function for the report is something like this:
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "XXXX";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2019-05-01");
$dateRange->setEndDate("2019-05-31");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");
$users = new Google_Service_AnalyticsReporting_Metric();
$users->setExpression("ga:users");
$users->setAlias("users");
$newSessions = new Google_Service_AnalyticsReporting_Metric();
$newSessions->setExpression("ga:percentNewSessions");
$newSessions->setAlias("newSessions");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions,$users,$newSessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
Of course is not the definitely one I'm just experimenting with some metrics.
I was trying to get back the users per day like this
$monthusers = new Google_Service_AnalyticsReporting_Metric();
$monthusers->setExpression("ga:30dayUsers");
$monthusers->setAlias("monthusers");
and then in the request
$request->setMetrics(array($sessions,$users,$newSessions,$monthusers));
but it throw a 500 error, any idea on how to get back the users per day? and based on the:
$dateRange->setStartDate("2019-05-01");
$dateRange->setEndDate("2019-05-31");
As per mentioned in the Dimensions & Metrics Explorer for the metric "ga:30dayUsers":
At least one of ga:nthDay, ga:date, or ga:day must be specified as a
dimension to query this metric.
You could use the ga:day dimension into your report request to solve the issue:
$day = new Google_Service_AnalyticsReporting_Dimension();
$day->setName("ga:day");
$request->setDimensions(array($day));
Currently I'm using the Google Sheets API via their PHP library to build a dynamic spreadsheet. I've set validation rules on a spreadsheet, specifically to create a dropdown list of states to select.
I have since updated the spreadsheet to have the state dropdown list in a different column. Upon doing this however, it seems the DataValidationRule that was set for the previous column, is still there.
I've attempted to create a method to REMOVE all validation from my sheet before re-applying any validation I want, but it does not seem to be working.
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#conditiontype
When setting a Condition Type, I'd like to revert the validation back to CONDITION_TYPE_UNSPECIFIED, however the API simply returns an error if I do so. I've attempted to use others such as ONE_OF_LIST, but then every cell errors saying:
Invalid: Input must be an item on specified list
Which makes sense, considering there is no list being generated (nor do I want one).
The rest of the columns can be any sort of combination of numbers/dates/text so I'd like to simply remove all validation before applying validation again.
Here's my current clearValidation code:
public function clearSpreadsheetValidations($spreadsheetId) {
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
$conditions = new Google_Service_Sheets_BooleanCondition();
$conditions->setType('CONDITION_TYPE_UNSPECIFIED');
$conditions->setValues(null);
$setRule= new Google_Service_Sheets_DataValidationRule();
$setRule->setCondition($conditions);
$setRule->setInputMessage(null);
$setRule->setShowCustomUi(false);
$valReq = new Google_Service_Sheets_SetDataValidationRequest();
$valReq->setRule($setRule);
$sheetReq = new Google_Service_Sheets_Request();
$sheetReq->setSetDataValidation($valReq);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($sheetReq);
$service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
}
How can I call the sheets API to remove all previously set DataValidationRules in a spreadsheet?
Thanks!
Okay, as noted here
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request
SetDataValidationRequest
Sets a data validation rule to every cell in the range. To clear
validation in a range, call this with no rule specified.
So all I had to do, was simply not declare a range, or set a rule, and ran this method on the existing spreadsheet to clear all existing validations
public function clearSpreadsheetValidations($spreadsheetId) {
$client = $this->getSheetsClient();
$service = new Google_Service_Sheets($client);
$valReq = new Google_Service_Sheets_SetDataValidationRequest();
$sheetReq = new Google_Service_Sheets_Request();
$sheetReq->setSetDataValidation($valReq);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($sheetReq);
$service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
}
For java this code worked in my case.
public BatchUpdateSpreadsheetResponse removeAllDataValidation(String spreadsheetId, Sheets service)
throws IOException {
// [START sheets_conditional_formatting]
List<Request> requests = Arrays.asList(new Request().setSetDataValidation(
new SetDataValidationRequest()));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse result = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
System.out.printf("%d cells updated.", result.getReplies().size());
// [END sheets_conditional_formatting]
return result;
}
I'm currently trying to obtain a list of the three most read articles on my site, using the Google Analytics Reporting API v4.
Currently, I have been able to request a list of all pages with the number of pageviews each one got in the past 30 days, and filter them by pageview.
But now I'm stuck (after browsing for answers for multiple hours) to filter so only pagepaths that include /artikels/ are shown, and limit the list to 3 results.
My current code:
function getReport($analytics) {
// Replace with your view ID, for example XXXX.
$VIEW_ID = "XXXXXXX";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("30daysAgo");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:pageviews");
$sessions->setAlias("sessions");
//Create the Dimensions object.
$pagepath = new Google_Service_AnalyticsReporting_Dimension();
$pagepath->setName("ga:pagePath");
$ordering = new Google_Service_AnalyticsReporting_OrderBy();
$ordering->setOrderType("VALUE");
$ordering->setFieldName("ga:pageviews");
$ordering->setSortOrder("DESCENDING");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($pagepath));
$request->setOrderBys($ordering);
$request->setMetrics(array($sessions));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
Could anyone please help? There is a ton of information about v3, but can't seem to find enough information about v4.
Thank you!
We have a PHP application and when we create an event in Google Calendar using de API, this event is generated without Hangout Link, but if we create the event manually, the event is created with the Hangout Link. The option to create automatically hangouts when we create an event is checked.
The code is:
$event = new Google_Service_Calendar_Event();
$event->setSummary($summary);
$event->setLocation('hangout');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($startDate->format(\DateTime::ISO8601));
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($endDate->format(\DateTime::ISO8601));
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($this->masterAccount);
$attendees= [];
$attendees[] = $attendee1;
foreach($company->getUsers()->toArray() as $user){
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($user->getEmail());
$attendees[] = $attendee1;
}
$event->attendees = $attendees;
$createdEvent = $this->google_calendar_service->events->insert($company->getCalendar()->getCalendarId(), $event);
If we use the form https://developers.google.com/google-apps/calendar/v3/reference/events/insert#try-it to create de Event, the hangout link is created without problems.
Any solutions?
Thanks :)
I know this topic is a bit old, but there are many people still struggling with making Calendar API work. After countless forums visited, hours of reading documentation and hitting my head against the wall I finally figured out, the key element is to set requestId.
In the time i've implemented this, this parameter wasn't mandatory and i skipped it.
Thats being said, my request looks like this:
$event = new Google_Service_Calendar_Event(); //creating empty event
$event->setSummary("Staff meeting"); //title
$event->setLocation("Room 101"); //location
$event->setDescription("We will talk about salary raise!"); //description
$event->setColorId(9); //make it shine by setting color
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($startDate->format(DateTime::ISO8601));
$start->setTimeZone('Europe/Warsaw');
$event->setStart($start); //set start
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($endDate->format(DateTime::ISO8601));
$end->setTimeZone('Europe/Warsaw');
$event->setEnd($end); //set end
$event->setGuestsCanSeeOtherGuests(false); //I dont want others to see who's invited
$event->setGuestsCanModify(false); //I dont want others to modify event
$event->setGuestsCanInviteOthers(false); //I dont want others to invite
$event->setAnyoneCanAddSelf(false); //I allow only people invited by me, not some strangers walking by
//this part should be executed in loop, for every guest
$attendee = new Google_Service_Calendar_EventAttendee();
$attendee->setEmail("staffmeber1#mywebsite.com");
$attendee->setResponseStatus('accepted');
$attendees[] = $attendee;
//When the list is completed, set guests in event
$event->setAttendees($attendees);
//The most important part about creating hangout
$conferenceData = new Google_Service_Calendar_ConferenceData(); //defining we have conference
$req = new Google_Service_Calendar_CreateConferenceRequest(); //requesting google to create video meeting
$req->setRequestId("req_".time()); //some random string/number changed every call. according to docs subsequent calls with the same request id are ignored
$conferenceData->setCreateRequest($req); //set request for videoconference in conference data
$event->setConferenceData($conferenceData); //set conference data in out event
$creator = new Google_Service_Calendar_EventCreator();
$creator->setDisplayName("Big boss");
$creator->setEmail('boss#mywebsite.com');
$event->setCreator($creator);
$event->setStatus('confirmed'); //lets say everyone is attending :D
$result = $this->calendarClient->events->insert($this->calendarObject->getId(), $event, ['conferenceDataVersion' => 1, 'sendUpdates' => "none"]); //dont forget about conferenceDataVersion or every conference data will be ignored
Working with Python here also faced issue, of events not being created with Hangouts. It seems settings can not be changed from program, but as SGC pointed out, I just changed google calendar settings from UI to add hangouts on every event created.