Apps Script Code Samples

  • This guide explains how to enable the YouTube Data API and YouTube Analytics API to run code samples within Apps Script.

  • The provided Apps Script function exports YouTube Analytics data, such as views, likes, dislikes, and shares, for the authenticated user's channel over the last 30 days.

  • The exported data is automatically populated into a new Google Sheet in the user's Drive, formatted with a stacked column chart for visualization.

  • The Google Sheet is named with 'YouTube Report' and the specified date range for the data.

To run code samples, you need to enable the YouTube Data API and YouTube Analytics API (v2) in Apps Script. The Data API quickstart explains how to add a service.

Export YouTube Analytics data to Google Sheets

This function uses the YouTube Analytics API to fetch data about the authenticated user's channel, creating a new Google Sheet in the user's Drive with the data.

The first part of this sample demonstrates a simple YouTube Analytics API call. This function first fetches the active user's channel ID. Using that ID, the function makes a YouTube Analytics API call to retrieve views, likes, dislikes and shares for the last 30 days. The API returns the data in a response object that contains a 2D array.

The second part of the sample constructs a Spreadsheet. This spreadsheet is placed in the authenticated user's Google Drive with the name 'YouTube Report' and date range in the title. The function populates the spreadsheet with the API response, then locks columns and rows that will define a chart axes. A stacked column chart is added for the spreadsheet.

functionspreadsheetAnalytics(){
//GetthechannelID
varmyChannels=YouTube.Channels.list('id',{mine:true});
varchannel=myChannels.items[0];
varchannelId=channel.id;

//Setthedatesforourreport
vartoday=newDate();
varoneMonthAgo=newDate();
oneMonthAgo.setMonth(today.getMonth()-1);
vartodayFormatted=Utilities.formatDate(today,'UTC','yyyy-MM-dd')
varoneMonthAgoFormatted=Utilities.formatDate(oneMonthAgo,'UTC','yyyy-MM-dd');

//TheYouTubeAnalytics.Reports.query()functionhasfourrequiredparametersandoneoptional
//parameter.Thefirstparameteridentifiesthechannelorcontentownerforwhichyouare
//retrievingdata.Thesecondandthirdparametersspecifythestartandenddatesforthe
//report,respectively.Thefourthparameteridentifiesthemetricsthatyouareretrieving.
//Thefifthparameterisanobjectthatcontainsanyadditionaloptionalparameters
//(dimensions,filters,sort,etc.)thatyouwanttoset.
varanalyticsResponse=YouTubeAnalytics.Reports.query({
"startDate":oneMonthAgoFormatted,
"endDate":todayFormatted,
"ids":"channel=="+channelId,
"dimensions":"day",
"sort":"-day",
"metrics":"views,likes,dislikes,shares"
});

//CreateanewSpreadsheetwithrowsandcolumnscorrespondingtoourdates
varssName='YouTube channel report '+oneMonthAgoFormatted+' - '+todayFormatted;
varnumRows=analyticsResponse.rows.length;
varnumCols=analyticsResponse.columnHeaders.length;

//Addanextrarowforcolumnheaders
varssNew=SpreadsheetApp.create(ssName,numRows+1,numCols);

//Getthefirstsheet
varsheet=ssNew.getSheets()[0];

//Gettherangeforthetitlecolumns
//Remember,spreadsheetsare1-indexed,whereasarraysare0-indexed
varheadersRange=sheet.getRange(1,1,1,numCols);
varheaders=[];

//Thesecolumnheaderswillcorrespondwiththemetricsrequested
//intheinitialcall:views,likes,dislikes,shares
for(variinanalyticsResponse.columnHeaders){
varcolumnHeader=analyticsResponse.columnHeaders[i];
varcolumnName=columnHeader.name;
headers[i]=columnName;
}
//Thistakesa2dimensionalarray
headersRange.setValues([headers]);

//Boldandfreezethecolumnnames
headersRange.setFontWeight('bold');
sheet.setFrozenRows(1);

//Getthedatarangeandsetthevalues
vardataRange=sheet.getRange(2,1,numRows,numCols);
dataRange.setValues(analyticsResponse.rows);

//Boldandfreezethedates
vardateHeaders=sheet.getRange(1,1,numRows,1);
dateHeaders.setFontWeight('bold');
sheet.setFrozenColumns(1);

//Includetheheadersinourrange.Theheadersareused
//tolabeltheaxes
varrange=sheet.getRange(1,1,numRows,numCols);
varchart=sheet.newChart()
.asColumnChart()
.setStacked()
.addRange(range)
.setPosition(4,2,10,10)
.build();
sheet.insertChart(chart);

}

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年08月28日 UTC.