Apps Script Code Samples
Stay organized with collections
Save and categorize content based on your preferences.
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.
function
spreadsheetAnalytics
()
{
//
Get
the
channel
ID
var
myChannels
=
YouTube
.
Channels
.
list
(
'id'
,
{
mine
:
true
}
);
var
channel
=
myChannels
.
items
[
0
]
;
var
channelId
=
channel
.
id
;
//
Set
the
dates
for
our
report
var
today
=
new
Date
();
var
oneMonthAgo
=
new
Date
();
oneMonthAgo
.
setMonth
(
today
.
getMonth
()
-
1
);
var
todayFormatted
=
Utilities
.
formatDate
(
today
,
'UTC'
,
'yyyy-MM-dd'
)
var
oneMonthAgoFormatted
=
Utilities
.
formatDate
(
oneMonthAgo
,
'UTC'
,
'yyyy-MM-dd'
);
//
The
YouTubeAnalytics
.
Reports
.
query
()
function
has
four
required
parameters
and
one
optional
//
parameter
.
The
first
parameter
identifies
the
channel
or
content
owner
for
which
you
are
//
retrieving
data
.
The
second
and
third
parameters
specify
the
start
and
end
dates
for
the
//
report
,
respectively
.
The
fourth
parameter
identifies
the
metrics
that
you
are
retrieving
.
//
The
fifth
parameter
is
an
object
that
contains
any
additional
optional
parameters
//
(
dimensions
,
filters
,
sort
,
etc
.)
that
you
want
to
set
.
var
analyticsResponse
=
YouTubeAnalytics
.
Reports
.
query
(
{
"startDate"
:
oneMonthAgoFormatted
,
"endDate"
:
todayFormatted
,
"ids"
:
"channel=="
+
channelId
,
"dimensions"
:
"day"
,
"sort"
:
"-day"
,
"metrics"
:
"views,likes,dislikes,shares"
}
);
//
Create
a
new
Spreadsheet
with
rows
and
columns
corresponding
to
our
dates
var
ssName
=
'YouTube channel report '
+
oneMonthAgoFormatted
+
' - '
+
todayFormatted
;
var
numRows
=
analyticsResponse
.
rows
.
length
;
var
numCols
=
analyticsResponse
.
columnHeaders
.
length
;
//
Add
an
extra
row
for
column
headers
var
ssNew
=
SpreadsheetApp
.
create
(
ssName
,
numRows
+
1
,
numCols
);
//
Get
the
first
sheet
var
sheet
=
ssNew
.
getSheets
()
[
0
]
;
//
Get
the
range
for
the
title
columns
//
Remember
,
spreadsheets
are
1
-
indexed
,
whereas
arrays
are
0
-
indexed
var
headersRange
=
sheet
.
getRange
(
1
,
1
,
1
,
numCols
);
var
headers
=
[]
;
//
These
column
headers
will
correspond
with
the
metrics
requested
//
in
the
initial
call
:
views
,
likes
,
dislikes
,
shares
for
(
var
i
in
analyticsResponse
.
columnHeaders
)
{
var
columnHeader
=
analyticsResponse
.
columnHeaders
[
i
]
;
var
columnName
=
columnHeader
.
name
;
headers
[
i
]
=
columnName
;
}
//
This
takes
a
2
dimensional
array
headersRange
.
setValues
(
[
headers
]
);
//
Bold
and
freeze
the
column
names
headersRange
.
setFontWeight
(
'bold'
);
sheet
.
setFrozenRows
(
1
);
//
Get
the
data
range
and
set
the
values
var
dataRange
=
sheet
.
getRange
(
2
,
1
,
numRows
,
numCols
);
dataRange
.
setValues
(
analyticsResponse
.
rows
);
//
Bold
and
freeze
the
dates
var
dateHeaders
=
sheet
.
getRange
(
1
,
1
,
numRows
,
1
);
dateHeaders
.
setFontWeight
(
'bold'
);
sheet
.
setFrozenColumns
(
1
);
//
Include
the
headers
in
our
range
.
The
headers
are
used
//
to
label
the
axes
var
range
=
sheet
.
getRange
(
1
,
1
,
numRows
,
numCols
);
var
chart
=
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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-28 UTC."],[[["\u003cp\u003eThis guide explains how to enable the YouTube Data API and YouTube Analytics API to run code samples within Apps Script.\u003c/p\u003e\n"],["\u003cp\u003eThe 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.\u003c/p\u003e\n"],["\u003cp\u003eThe exported data is automatically populated into a new Google Sheet in the user's Drive, formatted with a stacked column chart for visualization.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Sheet is named with 'YouTube Report' and the specified date range for the data.\u003c/p\u003e\n"]]],["The provided code exports YouTube Analytics data to a Google Sheet. It first retrieves the user's channel ID and then uses the YouTube Analytics API to query views, likes, dislikes, and shares for the past 30 days. It generates a new Google Sheet named \"YouTube Report,\" populates it with the API response data, including column headers for the metrics, locks the headers, and then generates a stacked column chart. Finally, it inserts the chart in the report.\n"],null,["# Apps Script Code Samples\n\nTo run code samples, you need to enable the YouTube Data API and YouTube Analytics API (v2) in Apps Script. The [Data API quickstart](https://developers.google.com/youtube/v3/quickstart/apps-script) explains how to add a service.\n\nExport YouTube Analytics data to Google Sheets\n----------------------------------------------\n\nThis 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. \n\nThe 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. \n\nThe 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. \n\n```transact-sql\n function spreadsheetAnalytics() {\n // Get the channel ID\n var myChannels = YouTube.Channels.list('id', {mine: true});\n var channel = myChannels.items[0];\n var channelId = channel.id;\n \n // Set the dates for our report\n var today = new Date();\n var oneMonthAgo = new Date();\n oneMonthAgo.setMonth(today.getMonth() - 1);\n var todayFormatted = Utilities.formatDate(today, 'UTC', 'yyyy-MM-dd')\n var oneMonthAgoFormatted = Utilities.formatDate(oneMonthAgo, 'UTC', 'yyyy-MM-dd');\n \n // The YouTubeAnalytics.Reports.query() function has four required parameters and one optional\n // parameter. The first parameter identifies the channel or content owner for which you are\n // retrieving data. The second and third parameters specify the start and end dates for the\n // report, respectively. The fourth parameter identifies the metrics that you are retrieving.\n // The fifth parameter is an object that contains any additional optional parameters\n // (dimensions, filters, sort, etc.) that you want to set.\n var analyticsResponse = YouTubeAnalytics.Reports.query({\n \"startDate\": oneMonthAgoFormatted,\n \"endDate\": todayFormatted,\n \"ids\": \"channel==\" + channelId,\n \"dimensions\": \"day\",\n \"sort\": \"-day\",\n \"metrics\": \"views,likes,dislikes,shares\"\n });\n \n // Create a new Spreadsheet with rows and columns corresponding to our dates\n var ssName = 'YouTube channel report ' + oneMonthAgoFormatted + ' - ' + todayFormatted;\n var numRows = analyticsResponse.rows.length;\n var numCols = analyticsResponse.columnHeaders.length;\n \n // Add an extra row for column headers\n var ssNew = SpreadsheetApp.create(ssName, numRows + 1, numCols);\n \n // Get the first sheet\n var sheet = ssNew.getSheets()[0];\n \n // Get the range for the title columns\n // Remember, spreadsheets are 1-indexed, whereas arrays are 0-indexed\n var headersRange = sheet.getRange(1, 1, 1, numCols);\n var headers = [];\n \n // These column headers will correspond with the metrics requested\n // in the initial call: views, likes, dislikes, shares\n for(var i in analyticsResponse.columnHeaders) {\n var columnHeader = analyticsResponse.columnHeaders[i];\n var columnName = columnHeader.name;\n headers[i] = columnName;\n }\n // This takes a 2 dimensional array\n headersRange.setValues([headers]);\n \n // Bold and freeze the column names\n headersRange.setFontWeight('bold');\n sheet.setFrozenRows(1);\n \n // Get the data range and set the values\n var dataRange = sheet.getRange(2, 1, numRows, numCols);\n dataRange.setValues(analyticsResponse.rows);\n \n // Bold and freeze the dates\n var dateHeaders = sheet.getRange(1, 1, numRows, 1);\n dateHeaders.setFontWeight('bold');\n sheet.setFrozenColumns(1);\n \n // Include the headers in our range. The headers are used\n // to label the axes\n var range = sheet.getRange(1, 1, numRows, numCols);\n var chart = sheet.newChart()\n .asColumnChart()\n .setStacked()\n .addRange(range)\n .setPosition(4, 2, 10, 10)\n .build();\n sheet.insertChart(chart);\n \n }\n```"]]