Note: Although this answer deals with YouTube reporting api, the flow should be the same for all Google apis, where advanced Google service wrapper isn't provided.
AFAICT, YouTube reporting API isn't directly available as a advanced Google service. You may be able to use YouTubeanalytics api, which is provided as a advanced Google service. To access reporting api, You need to directly connect to the api through HTTP calls and urlfetch.
Required reading:
Solution:
- It is possible to access YouTube reporting api from Google apps script using
UrlFetchApp
- Full OAuth flow can be bypassed using oauth token provided by
ScriptApp
- Include scopes in the appsscript.json manifest file.
- Switch to a standard GCP and enable the YouTube reporting api for this project. Otherwise 403 will be returned.
Snippet:
/**
* @description A wrapper for accessing Google apis from apps script
* @param {string} url Google URL endpoint
* @param {string} method HTTP method
* @param {object} requestBody Requestbody to send
* @param {object} pathParameters Parameters to modify in the url
* @param {object} queryParameters Queryparameters to append to the url
* @return {object} response
*/
function accessGoogleApiHTTP_(
url,
method,
requestBody = {},
pathParameters = {},
queryParameters = {}
) {
const modifiedUrl = Object.entries(pathParameters).reduce(
(acc, [key, value]) => acc.replace(key, value),
url
);
const queryUrl = Object.entries(queryParameters).reduce(
(acc, param) => acc + param.map(e => encodeURIComponent(e)).join('='),
'?'
);
const options = {
method,
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}` /*Need to set explicit scopes*/,
},
muteHttpExceptions: true,
payload: JSON.stringify(requestBody),
};
const res = UrlFetchApp.fetch(
modifiedUrl + queryUrl,
options
).getContentText();
console.log(res);
return JSON.parse(res);
}
/**
* @see https://developers.google.com/youtube/reporting/v1/reference/rest/v1/jobs/create
* @description POST https://youtubereporting.googleapis.com/v1/jobs
*/
function createYtReportingJob() {
const reportTypeId = 'id',
name = 'name';
const jsonRes = accessGoogleApiHTTP_(
'https://youtubereporting.googleapis.com/v1/jobs',
'POST',
{ reportTypeId, name },
undefined,
{ onBehalfOfContentOwner: 'contentOwnerId' }
);
}
Manifest scopes:
"oauthScopes": [
"https://www.googleapis.com/auth/yt-analytics",
"https://www.googleapis.com/auth/script.external_request"
]