YouTube Analytics and Reporting API with Google Apps Script - google-apps-script

I'm trying to use the YouTube Analytics and Reporting API with Google Apps Script to populate a Google Sheet with analytics data from YouTube brand accounts that I own and manage.
As a preface, I have tried this on YouTube channels that I own and channels that I manage and nothing has worked. I have also taken a look at all of the Stack Overflow questions & responses related to this for the past few days and nothing has worked. Believe me when I say I have tried everything. I do not believe the code or the way I set things up is the issue; I believe it has to do with Google or the YouTube API itself.
Here are the steps I have taken:
Enable the YouTube Analytics API and YouTube Data API in Google Apps Script. (The YouTube Reporting API is nowhere to be found which may be the issue...)
Enable the same APIs in Google Developer Console (The YouTube Reporting API is available there)
Set up a Client ID & Secret and linked my project to the Apps Script
Verified that my code indeed works by inputting the same exact parameters (metrics, dimensions, etc.) in the YouTube Analytics and Reporting API Explorer in Google Developer Console. When I do this, the explorer does indeed export the right information. However, in Google Apps Script, it does not work at all.
Due to the fact that the code works in the Explorer, but not in Google Apps Script, I believe that there's something simple that I'm doing wrong, or it's an error on the Google side. I'm hoping that there's a way around this or a fix, because I'd really like to get the data from my YouTube channels into Google Sheets.
Google Apps Script code (shortened for simplicity. The "key" property may not be necessary, but it doesn't work without it either).
function myFunction() {
var metrics = [
'averageViewDuration'
];
var oneMonthInMillis = 1000 * 60 * 60 * 24 * 30;
var today = new Date();
var lastMonth = new Date(today.getTime() - oneMonthInMillis);
var report = YouTubeAnalytics.Reports.query({
ids: 'channel==MINE',
startDate: formatDateString(lastMonth),
endDate: formatDateString(today),
metrics: metrics.join(','),
dimensions: 'day',
sort: 'day',
includeHistoricalChannelData: false,
key: "AIzaSyAcVb-hriIydRs8iVqFZ6ZoyL8En3qLcnc",
});
Logger.log(report);
}
When I run the code, there is zero output to the logger. I expect there to be something there.
As a reminder, this happens when I select any account besides my core account. When I select the core account attached to the account (that does not have a YouTube channel), it does output this:
"[19-10-30 17:58:19:251 PDT] {columnHeaders=[{columnType=DIMENSION,
dataType=STRING, name=day}, {columnType=METRIC, dataType=INTEGER,
name=averageViewDuration}], kind=youtubeAnalytics#resultTable,
rows=[[2019-09-30, 0], [2019-10-01, 0], [2019-10-02, 0], [2019-10-03,
0], [2019-10-04, 0], [2019-10-05, 0], [2019-10-06, 0], [2019-10-07,
0], [2019-10-08, 0]...]]}"
There's no reason that it shouldn't be working. What do you think is the issue?

Sorry, but currently what you would want to do, it's not supported by Apps Script. It was already reported in Google Issue tracker, as you can see in the next links:
Youtube Data api v3 can not authenticate by brand account in gas
The YouTube API Will Not Authorize a Google+ Page's YouTube Channel
YouTube.Videos.update throws Forbidden exception for any video on secondary channel
As a workaround, you can implement Oauth2.0 as it is said in this Stack Overflow's post
Edit
If you are having troubles using the refresh token, Use this code to make the request directly to the Youtube API after obtaining an access token from Oauth2.0 playground
function makeRequest() {
var response = UrlFetchApp.fetch('https://youtubeanalytics.googleapis.com/v2/reports?endDate=2019-10-10&ids=channel%3D%3DMINE&metrics=views&startDate=2019-10-09', {
headers: {
// you will get the access token from Oauth2.0 playground
Authorization: 'Bearer ACCES_TOKEN'
}
});
Logger.log(response)
}
From The YouTube API Will Not Authorize a Google+ Page's YouTube Channel, it says
The engineering team has decided that it's not possible to support
this use case. You'll need to use something other than the YouTube
advanced service to access a channel owned by a G+ page.
So, it seems there is no support for what you want

Related

Will the Google Apps Script Contacts Service (ContactsApp) still work after the People API migration?

Google is migrating the Contacts API to the new People API beginning in June 2021. In some of my Google Apps Scripts I use the ContactsApp class from the Contacts Service (https://developers.google.com/apps-script/reference/contacts). Will this service still will work after the migration to the new People API?
Answer:
Apps Script acts as a client to the Contacts API and will receive the same error rates as all other clients.
More Information:
After the sunset of Contacts API, any errors that would be returned when trying to use it will be seen no matter how it is called - be that a client library, the Apps Script wrapper, or just HTTP requests.
Google sent out an email recently informing of the change - and this should have been received regardless of whether they are using Contacts API directly, or have Apps Script projects which use it.
At the moment it doesn't seem that there are any plans for a PeopleService or equivalent - but the Apps Script Advanced Services do have People API integration.
I would also urge you to make a feature request for a PeopleService equivalent of ContactsService, if you would like to see something like this implemented. You can file a feature request for this here on Google's Issue Tracker under the Apps Script Feature Request component.
To answer this question, No. It does not still work. I am in the middle of refactoring my code because it doesn't work anymore. I am trying to get a list of contacts from Google Contacts that have a specific label and now with the migration, I have not idea how to do this.

Youtube Quota on new Project

I am using the Youtube API with Apps Script for the first time but I get a quota error. I activated the Youtube API from the Apps Script window, and added my scripts.
Note I am using a Google Workspace account. I didn't have this problem with my private google account.
Here is the code that generates the error:
function getVids() {
var list = YouTube.Search.list('id,snippet', {
channelId: 'UCYf_kU_HoMOUUe3hW-0ou5Q',
maxResults: 25
})
var json = JSON.parse(list);
var items = list.items;
var allVideos = [];
for (var i=1; i<items.length;i++) {
var videoId = list.items[i].id.videoId;
allVideos.push(videoId);
}
console.log(allVideos)
}
I receive this error:
GoogleJsonResponseException: API call to youtube.videos.insert failed
with error: The request cannot be completed because you have exceeded
your quota.
I tried looking at the consumption here: https://console.developers.google.com/apis/dashboard but it redirects me to https://console.developers.google.com/apis/dashboard?project=northern-math-286006&folder=&organizationId= which I assume is some default project name as I didn't choose it. I selected https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?folder=&organizationId=&project=northern-math-286006 from this page to view Youtube data but it returns "No data is available for the selected time frame."
Explanation:
According to the official documentation you have exceeded 10,000 units per day.
Unit points might be a little tricky to understand but there is a very good explanation on the link above itself:
You are doing SEARCH requests and for every search request you spend 100 units. I assume you have executed this code and/or other codes that consume points and this is why you reached your maximum unit points.
According to the documentation here you can see your quota usage but you might need to have permission to access that info.
YouTube Data API (v3) - Quota Calculator:
If your application calls a method, such as search.list, that returns
multiple pages of results, each request to retrieve an additional page
of results incurs the estimated quota cost.
Did you check your quota for this API? You can find your quotas under 'IAM &A Admin' -> Quotas. Then look for 'YouTube Data API V3'.
Click on the one saying 'Queries per day' and see if the Limit is set to 0.
If yes, you might try to disable this API and enable again.
I had this issue too, and after disabling and enabling the API I get the 10k units.

Google My Maps - API

Is there any way to add Layers, Points, Directions or any data to a map in the Google My Maps, using API?
I have searched in Google but didn't find a solution to do this.
Currently there is no any API to access MyMaps programmatically.
I can see a feature request for this in the public issue tracker:
https://issuetracker.google.com/issues/35820262
It looks like Google is evaluating the feasibility to implement the API, however, no timeline provided at the moment.
Please star this feature request to express your interest and receive further updates.
UPDATE
As of April 2018 it looks like Google decided do not implement the API for Google MyMaps and marked the aforementioned feature request as Infeasible.
This is not a fantastic solution — and it does not use the API — but it might fit your needs. Instead of using the API you could write a browser console script that adds each new item. You could probably even run this through a headless browser and remove any manual interaction altogether.
eg.
fetch('https://example.com/newLocations')
.then((response) => response.json())
.then((newLocations) => {
newLocations.forEach(location => {
document.querySelector("#mapsprosearch-field").value = location.name + ", " + location.city;
document.querySelector("#mapsprosearch-button > div").click();
document.querySelector("#addtomap-button").click();
// etc.
});
});
—
UPDATE
Re-opened as of Feb 2021 — API support for this has been assigned. So hopefully we get support soon!
https://issuetracker.google.com/issues/35820262

Google Places Autocomplete API Consumption

I'm using google maps API on my company, and we're facing some issues with the consumption of the API.
We use the Javascript API, loading the map, and we geocode some address and make some routes. Everything normal.
But we use the Autocomplete in some cases, to allow the user to input the location he's searching.
So, I define the autocomplete like this:
var autocomplete = new google.maps.places.Autocomplete(
document.getElementById('textBox'),
{ types: [] });
When the user select an option, we call the function
autocomplete.addListener('place_changed', doSomething);
get the place and do more things
function doSomething() { var place =
autocomplete.getPlace();
//more code }
Everything works fine, but when the user start typing, it's been consuming the Google Places API Web Service. Is it right?
I thought it would only consume the Javascript API when we loads the map, and that's it.
And the weird thing is that, on the developer's console, the utilization of the API started few days ago (30/06/2016), and we have a gap of no utilization of this API (between 3th and 10th of July), and yesterday we reach the limit of 1000 uses.
Am I doing something wrong? What can I do?
Sorry if this is not the right place for the question, and if it's not, move it or tell me so I can open in the new place.
Thanks
You can find an answer in this blog post:
http://googlegeodevelopers.blogspot.com.es/2016/06/building-for-scale-updates-to-google.html
Look at 4. Starting from June 22, 2016 Google counts client-side requests against the corresponding web service APIs. Apparently, some of your domains were "grandfathered", but the new ones will follow the new policy.

Understanding the authorization flow with Google Drive and Google Play Services

I have gone through Quickstart with Google Drive and I have also used Google Play Services. The docs for Google Drive outline the process of how the authorization flow works. The docs also indicate that developers should not use Drive initiated authorization although it appears that the Quickstart sample app does exactly that. I am left with the impression that Google prefers that the developer handle all the details of authorization.
Yet after trying out sample code that uses Google Play Services (but not for Google Drive), I am left with the impression that Google wants developers to use Google Play Services to handle all the authorization. It seems that Google Play Services simplify the authorization process significantly. Although the docs don't say this, I found elsewhere online that GoogleAuthUtil.getToken manages how access and refresh tokens are retrieved, especially after they expire.
Basically, the issue I am struggling with to understand is whether the Google Drive docs for the API are out of date and Google wants us to rely upon Google Play Services. There seems to be a lot of complexity in the Google Drive authorization process that Google Play Services has eliminated. At the same time, the docs for Google Drive API has been available for over half a year, so it makes me question why Google hasn't updated these docs to show any reflection on how Google Play Services are used with it.
Any insight into this would be appreciated.
The recommended approach for authorization on Android is using Google Play Services. The Android quickstart guide on the Google Drive SDK documentation covers exactly that:
https://developers.google.com/drive/quickstart-android
The Google Drive docs are out of date and Google should really update them. Retrieving tokens and authenticating users should be done using Google Play Services. The only thing you should be using the Google Drive API for is accessing the Google Drive service. Google Play Services handles all the details of authenticating users, retrieving access and refresh tokens and handling all the errors that can arise.