Apps Script Code Samples

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(){//GetthechannelIDvarmyChannels=YouTube.Channels.list('id',{mine:true});varchannel=myChannels.items[0];varchannelId=channel.id;//Setthedatesforourreportvartoday=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"});//CreateanewSpreadsheetwithrowsandcolumnscorrespondingtoourdatesvarssName='YouTube channel report '+oneMonthAgoFormatted+' - '+todayFormatted;varnumRows=analyticsResponse.rows.length;varnumCols=analyticsResponse.columnHeaders.length;//AddanextrarowforcolumnheadersvarssNew=SpreadsheetApp.create(ssName,numRows+1,numCols);//Getthefirstsheetvarsheet=ssNew.getSheets()[0];//Gettherangeforthetitlecolumns//Remember,spreadsheetsare1-indexed,whereasarraysare0-indexedvarheadersRange=sheet.getRange(1,1,1,numCols);varheaders=[];//Thesecolumnheaderswillcorrespondwiththemetricsrequested//intheinitialcall:views,likes,dislikes,sharesfor(variinanalyticsResponse.columnHeaders){varcolumnHeader=analyticsResponse.columnHeaders[i];varcolumnName=columnHeader.name;headers[i]=columnName;}//Thistakesa2dimensionalarrayheadersRange.setValues([headers]);//BoldandfreezethecolumnnamesheadersRange.setFontWeight('bold');sheet.setFrozenRows(1);//GetthedatarangeandsetthevaluesvardataRange=sheet.getRange(2,1,numRows,numCols);dataRange.setValues(analyticsResponse.rows);//BoldandfreezethedatesvardateHeaders=sheet.getRange(1,1,numRows,1);dateHeaders.setFontWeight('bold');sheet.setFrozenColumns(1);//Includetheheadersinourrange.Theheadersareused//tolabeltheaxesvarrange=sheet.getRange(1,1,numRows,numCols);varchart=sheet.newChart().asColumnChart().setStacked().addRange(range).setPosition(4,2,10,10).build();sheet.insertChart(chart);}