问题描述
如何在Google Apps脚本中使用'Job' resource?
我了解必须启用YouTube Reporting API,但是可以从哪个对象调用它?
我正在尝试访问YouTube Reporting API。这是正确的调用方式吗? 如果是这样,我的Apps脚本无法识别youtubeReporting,为什么会这样?
youtubeReporting.jobs()
总而言之,我的目标是提取“内容拥有者报告”批量/查询,几乎要读到导致该内容的所有步骤,除了最开始就是对象名。
解决方法
注意:尽管此答案涉及YouTube报告api,但对于未提供高级Google服务包装程序的所有Google api,其流程应相同。
AFAICT,YouTube报表API不能直接作为高级Google服务使用。您可能可以使用YouTubeanalytics api,which is provided as a advanced Google service。要访问报告api,您需要directly connect to the api through HTTP calls和urlfetch。
必读:
解决方案:
- 可以使用
UrlFetchApp
从Google Apps脚本访问YouTube报告API。
- 可以使用
ScriptApp
提供的oauth令牌绕过完整的OAuth流 - 将范围包括在appsscript.json清单文件中。
- 切换到标准GCP并为此项目启用YouTube报告API。否则将返回403。
摘要:
/**
* @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' }
);
}
清单范围:
"oauthScopes": [
"https://www.googleapis.com/auth/yt-analytics","https://www.googleapis.com/auth/script.external_request"
]
,
答案
要访问YouTube报表API,您必须添加 YouTube Analytics API ,还可以选择添加 YouTube Data API 。此时,您可以像Apps Script: YouTube Analytics示例中那样创建报告。
记住:
-
导入诸如 YouTube Analytics API 之类的服务时,请注意版本。
-
您可以指定所需的指标数量。
参考
Apps Script: YouTube Analytics