Apps Script Code Samples

  • These code samples, available on GitHub, demonstrate various interactions with the YouTube Data API using Apps Script.

  • The retrieveMyUploads function retrieves a user's uploaded videos, requiring OAuth read/write scope and user authorization, iterating through the user's 'uploads' playlist and logging video details.

  • searchByKeyword and searchByTopic functions demonstrate searching for videos based on keywords or Freebase topics, respectively, both with the option to adjust the number of results.

  • The addSubscription function allows users to subscribe to a specified YouTube channel, providing error handling for duplicate subscription attempts.

  • The updateVideo function illustrates how to modify the description of the most recent video uploaded by the active user.

The following Apps Script code samples are available for the YouTube Data API. You can download these code samples from the apps-script folder of the YouTube APIs code sample repository on GitHub.

Retrieve my uploads

This function retrieves the current script user's uploaded videos. To execute, it requires the OAuth read/write scope for YouTube as well as user authorization. In Apps Script's runtime environment, the first time a user runs a script, Apps Script will prompt the user for permission to access the services called by the script. After permissions are granted, they are cached for some period of time. The user running the script will be prompted for permission again once the permissions required change, or when they are invalidated by the ScriptApp.invalidateAuth() function.

This script takes the following steps to retrieve the active user's uploaded videos:
  1. Fetches the user's channels.
  2. Fetches the user's 'uploads' playlist.
  3. Iterates through this playlist and logs the video IDs and titles.
  4. Fetches a next page token, if any. If there is one, fetches the next page. Repeat step 3.
/**
*Thisfunctionretrievesthecurrentscriptuser's uploaded videos. To execute,
*itrequirestheOAuthread/writescopeforYouTubeaswellasuserauthorization.
*InAppsScript's runtime environment, the first time a user runs a script, Apps
*Scriptwillprompttheuserforpermissiontoaccesstheservicescalledbythe
*script.Afterpermissionsaregranted,theyarecachedforsomeperiodFoftime.
*Theuserrunningthescriptwillbepromptedforpermissionagainoncethe
*permissionsrequiredchange,orwhentheyareinvalidatedbythe
*ScriptApp.invalidateAuth()function.
*
*Thisscripttakesthefollowingstepstoretrievetheactiveuser's uploaded videos:
*1.Fetchestheuser's channels
*2.Fetchestheuser's 'uploads' playlist
*3.IteratesthroughthisplaylistandlogsthevideoIDsandtitles
*4.Fetchesanextpagetoken(ifany).Ifthereisone,fetchesthenextpage.GOTOStep3
*/
functionretrieveMyUploads(){
varresults=YouTube.Channels.list('contentDetails',{mine:true});
for(variinresults.items){
varitem=results.items[i];
//GettheplaylistID,whichisnestedincontentDetails,asdescribedinthe
//Channelresource:https://developers.google.com/youtube/v3/docs/channels
varplaylistId=item.contentDetails.relatedPlaylists.uploads;
varnextPageToken='';
//ThisloopretrievesasetofplaylistitemsandchecksthenextPageTokeninthe
//responsetodeterminewhetherthelistcontainsadditionalitems.Itrepeatsthatprocess
//untilithasretrievedalloftheitemsinthelist.
while(nextPageToken!=null){
varplaylistResponse=YouTube.PlaylistItems.list('snippet',{
playlistId:playlistId,
maxResults:25,
pageToken:nextPageToken
});
for(varj=0;j < playlistResponse.items.length;j++){
varplaylistItem=playlistResponse.items[j];
Logger.log('[%s] Title: %s',
playlistItem.snippet.resourceId.videoId,
playlistItem.snippet.title);
}
nextPageToken=playlistResponse.nextPageToken;
}
}
}

Search by keyword

This function searches for videos related to the keyword 'dogs'. The video IDs and titles of the search results are logged to Apps Script's log.

Note that this sample limits the results to 25. To return more results, pass additional parameters as documented in Search:list.
/**
 * This function searches for videos related to the keyword 'dogs'. The video IDs and titles
 * of the search results are logged to Apps Script's log.
 *
 * Note that this sample limits the results to 25. To return more results, pass
 * additional parameters as documented here:
 * https://developers.google.com/youtube/v3/docs/search/list
 */
functionsearchByKeyword(){
varresults=YouTube.Search.list('id,snippet',{q:'dogs',maxResults:25});
for(variinresults.items){
varitem=results.items[i];
Logger.log('[%s] Title: %s',item.id.videoId,item.snippet.title);
}
}

Search by topic

This function searches for videos that are associated with a particular Freebase topic, logging their video IDs and titles to the Apps Script log. This example uses the topic ID for Google Apps Script.

Note that this sample limits the results to 25. To return more results, pass additional parameters as documented in Search:list.
/**
 * This function searches for videos that are associated with a particular Freebase
 * topic, logging their video IDs and titles to the Apps Script log. This example uses
 * the topic ID for Google Apps Script.
 *
 * Note that this sample limits the results to 25. To return more results, pass
 * additional parameters as documented here:
 * https://developers.google.com/youtube/v3/docs/search/list
 */
functionsearchByTopic(){
varmid='/m/0gjf126';
varresults=YouTube.Search.list('id,snippet',{topicId:mid,maxResults:25});
for(variinresults.items){
varitem=results.items[i];
Logger.log('[%s] Title: %s',item.id.videoId,item.snippet.title);
}
}

Subscribe to channel

This sample subscribes the active user to the Google Developers YouTube channel, specified by the channelId.
/**
*ThissamplesubscribestheactiveusertotheGoogleDevelopers
*YouTubechannel,specifiedbythechannelId.
*/
functionaddSubscription(){
//ReplacethischannelIDwiththechannelIDyouwanttosubscribeto
varchannelId='UC_x5XG1OV2P6uZZ5FSM9Ttw';
varresource={
snippet:{
resourceId:{
kind:'youtube#channel',
channelId:channelId
}
}
};
try{
varresponse=YouTube.Subscriptions.insert(resource,'snippet');
Logger.log(response);
}catch(e){
if(e.message.match('subscriptionDuplicate')){
Logger.log('Cannot subscribe; already subscribed to channel: '+channelId);
}else{
Logger.log('Error adding subscription: '+e.message);
}
}
}

Update video

This sample finds the active user's uploads, then updates the most recent upload's description by appending a string.
/**
*Thissamplefindstheactiveuser's uploads, then updates the most recent
*upload's description by appending a string.
*/
functionupdateVideo(){
//1.Fetchallthechannelsownedbyactiveuser
varmyChannels=YouTube.Channels.list('contentDetails',{mine:true});
//2.IteratethroughthechannelsandgettheuploadsplaylistID
for(vari=0;i < myChannels.items.length;i++){
varitem=myChannels.items[i];
varuploadsPlaylistId=item.contentDetails.relatedPlaylists.uploads;
varplaylistResponse=YouTube.PlaylistItems.list('snippet',{
playlistId:uploadsPlaylistId,
maxResults:1
});
//GetthevideoIDofthefirstvideointhelist
varvideo=playlistResponse.items[0];
varoriginalDescription=video.snippet.description;
varupdatedDescription=originalDescription+' Description updated via Google Apps Script';
video.snippet.description=updatedDescription;
varresource={
snippet:{
title:video.snippet.title,
description:updatedDescription,
categoryId:'22'
},
id:video.snippet.resourceId.videoId
};
YouTube.Videos.update(resource,'id,snippet');
}
}

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 2026年06月01日 UTC.