├── README.md ├── apps-script ├── quickstart.gs ├── snippets │ ├── README.md │ └── apps-script.gs └── youtube.gs ├── dotnet ├── .gitignore ├── Google.Apis.YouTube.Samples.Playlists │ ├── .gitignore │ ├── App.config │ ├── Google.Apis.YouTube.Samples.Playlists.csproj │ ├── PlaylistUpdates.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── packages.config ├── Google.Apis.YouTube.Samples.Search │ ├── .gitignore │ ├── App.config │ ├── Google.Apis.YouTube.Samples.Search.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Search.cs │ └── packages.config ├── Google.Apis.YouTube.Samples.Upload │ ├── .gitignore │ ├── App.config │ ├── Google.Apis.YouTube.Samples.Upload.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── UploadVideo.cs │ └── packages.config ├── Google.Apis.YouTube.Samples.sln ├── MyUploads.cs ├── PlaylistUpdates.cs ├── README.md ├── Search.cs ├── UploadVideo.cs ├── client_secrets.json ├── dotnet.csproj ├── packages.config └── packages │ └── repositories.config ├── go ├── README.md ├── client_secrets.json.sample ├── errors.go ├── my_uploads.go ├── oauth2.go ├── playlists.go ├── quickstart.go ├── search_by_keyword.go └── upload_video.go ├── java ├── README.md ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── google │ │ └── api │ │ └── services │ │ └── samples │ │ └── youtube │ │ └── cmdline │ │ ├── Auth.java │ │ ├── analytics │ │ └── YouTubeAnalyticsReports.java │ │ ├── data │ │ ├── AddSubscription.java │ │ ├── Captions.java │ │ ├── ChannelBulletin.java │ │ ├── ChannelLocalizations.java │ │ ├── ChannelSectionLocalizations.java │ │ ├── CommentHandling.java │ │ ├── CommentThreads.java │ │ ├── GeolocationSearch.java │ │ ├── InvideoProgramming.java │ │ ├── MyUploads.java │ │ ├── PlaylistLocalizations.java │ │ ├── PlaylistUpdates.java │ │ ├── Quickstart.java │ │ ├── Search.java │ │ ├── UpdateVideo.java │ │ ├── UploadThumbnail.java │ │ ├── UploadVideo.java │ │ └── VideoLocalizations.java │ │ ├── live │ │ ├── CreateBroadcast.java │ │ ├── DeleteLiveChatMessage.java │ │ ├── GetLiveChatId.java │ │ ├── InsertLiveChatMessage.java │ │ ├── ListBroadcasts.java │ │ ├── ListLiveChatMessages.java │ │ └── ListStreams.java │ │ └── reporting │ │ ├── CreateReportingJob.java │ │ └── RetrieveReports.java │ └── resources │ ├── client_secrets.json │ ├── sample-video.mp4 │ ├── watermark.jpg │ └── youtube.properties ├── javascript ├── README.md ├── analytics_codelab.css ├── analytics_codelab.html ├── analytics_codelab.js ├── auth.js ├── cors_upload.js ├── my_uploads.css ├── my_uploads.html ├── my_uploads.js ├── nodejs-quickstart.js ├── playlist_updates.html ├── playlist_updates.js ├── quickstart.html ├── search.html ├── search.js ├── upload_video.css ├── upload_video.html ├── upload_video.js └── yt_analytics_v2.html ├── php ├── .gitignore ├── README.md ├── add_channel_section.php ├── add_subscription.php ├── captions.php ├── channel_localizations.php ├── channel_section_localizations.php ├── comment_handling.php ├── comment_threads.php ├── create_broadcast.php ├── create_reporting_job.php ├── geolocation_search.php ├── index.php ├── list_broadcasts.php ├── list_streams.php ├── my_uploads.php ├── playlist_localizations.php ├── playlist_updates.php ├── quickstart.php ├── resumable_upload.php ├── retrieve_reports.php ├── search.php ├── shuffle_channel_sections.php ├── tests │ └── ExamplesTest.php ├── update_video.php ├── upload_banner.php ├── upload_thumbnail.php └── video_localizations.php ├── player ├── demo.js ├── event_listeners.html ├── event_listeners.js ├── index.html ├── player_control.html └── player_control.js ├── python ├── README.md ├── add_channel_section.py ├── add_featured_video.py ├── add_subscription.py ├── captions.py ├── channel_bulletin.py ├── channel_localizations.py ├── channel_section_localizations.py ├── comment_handling.py ├── comment_threads.py ├── create_broadcast.py ├── create_reporting_job.py ├── geolocation_search.py ├── like_video.py ├── list_broadcasts.py ├── list_streams.py ├── my_uploads.py ├── playlist_localizations.py ├── playlist_updates.py ├── quickstart.py ├── quickstart_web.py ├── retrieve_reports.py ├── search.py ├── set_watermark.py ├── shuffle_channel_sections.py ├── unset_watermark.py ├── update_video.py ├── upload_banner.py ├── upload_thumbnail.py ├── upload_video.py ├── video_localizations.py ├── yt_analytics_report.py └── yt_analytics_v2.py ├── python_appengine ├── README.md ├── search │ ├── app.yaml │ ├── index.html │ └── main.py └── user_uploads │ ├── app.yaml │ ├── index.html │ └── main.py └── ruby ├── README.md ├── add_subscription.rb ├── channel_bulletin.rb ├── my_uploads.rb ├── oauth └── oauth_util.rb ├── quickstart.rb ├── search.rb ├── upload_video.rb └── yt_analytics_report.rb /README.md: -------------------------------------------------------------------------------- 1 | api-samples 2 | =========== 3 | 4 | Code samples for YouTube APIs, including the YouTube Data API, YouTube Analytics API, and YouTube Live Streaming API. The repo contains language-specific directories that contain the samples. 5 | -------------------------------------------------------------------------------- /apps-script/quickstart.gs: -------------------------------------------------------------------------------- 1 | // Note: Apps Script automatically requests authorization 2 | // based on the API's used in the code. 3 | 4 | function channelsListByUsername(part, params) { 5 | var response = YouTube.Channels.list(part, 6 | params); 7 | var channel = response.items[0]; 8 | var dataRow = [channel.id, channel.snippet.title, channel.statistics.viewCount]; 9 | SpreadsheetApp.getActiveSpreadsheet().appendRow(dataRow); 10 | } 11 | 12 | function getChannel() { 13 | var ui = SpreadsheetApp.getUi(); 14 | var channelName = ui.prompt("Enter the channel name: ").getResponseText(); 15 | channelsListByUsername('snippet,contentDetails,statistics', 16 | {'forUsername': channelName}); 17 | } 18 | 19 | function getGoogleDevelopersChannel() { 20 | channelsListByUsername('snippet,contentDetails,statistics', 21 | {'forUsername': 'GoogleDevelopers'}); 22 | } 23 | 24 | function onOpen() { 25 | var firstCell = SpreadsheetApp.getActiveSheet().getRange(1, 1).getValue(); 26 | if (firstCell != 'ID') { 27 | var headerRow = ["ID", "Title", "View count"]; 28 | SpreadsheetApp.getActiveSpreadsheet().appendRow(headerRow); 29 | } 30 | var ui = SpreadsheetApp.getUi(); 31 | ui.createMenu('YouTube Data') 32 | .addItem('Add channel data', 'getChannel') 33 | .addSeparator() 34 | .addItem('Add GoogleDevelopers data', 'getGoogleDevelopersChannel') 35 | .addToUi(); 36 | } 37 | -------------------------------------------------------------------------------- /apps-script/snippets/README.md: -------------------------------------------------------------------------------- 1 | # Apps Script Code Snippets 2 | 3 | The `youtube-data-api.gs` file in this directory contains code snippets that are generated 4 | by the Data API code snippet tool at: 5 | https://developers.google.com/youtube/v3/code_samples/code_snippets 6 | 7 | You can use that tool to test different parameter values and to generate code samples with 8 | those modified parameter values. The tool generates code for several other programming 9 | languages as well. 10 | 11 | Each function in the file demonstrates a particular use case for a particular API method. 12 | For example, there are several different use cases for calling the `search.list()` method, 13 | such as searching by keyword or searching for live events. 14 | 15 | In addition to the use-case-specific functions, the file also contains some boilerplate code 16 | that prints some data from an API response to the logging console. The print function is 17 | currently designed just to show that each API response returns data and serves as a placeholder 18 | for any function that would actually process an API response. 19 | 20 | ## Running these samples 21 | 22 | To run these samples: 23 | 24 | 1. Create a spreadsheet in [Google Drive](https://spreadsheets.google.com). 25 | 2. Select **Tools > Script Editor** from the menu bar. 26 | 3. Paste this code into the script editor and save your file. 27 | 4. In the script, select **Resources > Advanced Google Services** and toggle the option for the 28 | YouTube Data API to on. 29 | 5. Click the link to the Google Developers Console and enable the YouTube Data API for the project. 30 | 6. Go back to the script editor and click 'OK' to indicate that you have finished enabling advanced services. 31 | 7. Run the `Main` function in your script. 32 | 8. Select **View > Logs** to see the output from the script. 33 | -------------------------------------------------------------------------------- /dotnet/.gitignore: -------------------------------------------------------------------------------- 1 | *.suo 2 | *.user 3 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Playlists/.gitignore: -------------------------------------------------------------------------------- 1 | obj/ 2 | bin/ 3 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Playlists/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Playlists/PlaylistUpdates.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | using System; 19 | using System.IO; 20 | using System.Reflection; 21 | using System.Threading; 22 | using System.Threading.Tasks; 23 | 24 | using Google.Apis.Auth.OAuth2; 25 | using Google.Apis.Services; 26 | using Google.Apis.Upload; 27 | using Google.Apis.Util.Store; 28 | using Google.Apis.YouTube.v3; 29 | using Google.Apis.YouTube.v3.Data; 30 | 31 | namespace Google.Apis.YouTube.Samples 32 | { 33 | /// 34 | /// YouTube Data API v3 sample: create a playlist. 35 | /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. 36 | /// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted 37 | /// 38 | internal class PlaylistUpdates 39 | { 40 | [STAThread] 41 | static void Main(string[] args) 42 | { 43 | Console.WriteLine("YouTube Data API: Playlist Updates"); 44 | Console.WriteLine("=================================="); 45 | 46 | try 47 | { 48 | new PlaylistUpdates().Run().Wait(); 49 | } 50 | catch (AggregateException ex) 51 | { 52 | foreach (var e in ex.InnerExceptions) 53 | { 54 | Console.WriteLine("Error: " + e.Message); 55 | } 56 | } 57 | 58 | Console.WriteLine("Press any key to continue..."); 59 | Console.ReadKey(); 60 | } 61 | 62 | private async Task Run() 63 | { 64 | UserCredential credential; 65 | using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 66 | { 67 | credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( 68 | GoogleClientSecrets.Load(stream).Secrets, 69 | // This OAuth 2.0 access scope allows for full read/write access to the 70 | // authenticated user's account. 71 | new[] { YouTubeService.Scope.Youtube }, 72 | "user", 73 | CancellationToken.None, 74 | new FileDataStore(this.GetType().ToString()) 75 | ); 76 | } 77 | 78 | var youtubeService = new YouTubeService(new BaseClientService.Initializer() 79 | { 80 | HttpClientInitializer = credential, 81 | ApplicationName = this.GetType().ToString() 82 | }); 83 | 84 | // Create a new, private playlist in the authorized user's channel. 85 | var newPlaylist = new Playlist(); 86 | newPlaylist.Snippet = new PlaylistSnippet(); 87 | newPlaylist.Snippet.Title = "Test Playlist"; 88 | newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3"; 89 | newPlaylist.Status = new PlaylistStatus(); 90 | newPlaylist.Status.PrivacyStatus = "public"; 91 | newPlaylist = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync(); 92 | 93 | // Add a video to the newly created playlist. 94 | var newPlaylistItem = new PlaylistItem(); 95 | newPlaylistItem.Snippet = new PlaylistItemSnippet(); 96 | newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id; 97 | newPlaylistItem.Snippet.ResourceId = new ResourceId(); 98 | newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"; 99 | newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"; 100 | newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync(); 101 | 102 | Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Playlists/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Google.Apis.YouTube.Samples")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Google.Apis.YouTube.Samples")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("7c1fa4ce-316c-433b-9b87-af60a4da649e")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Playlists/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Search/.gitignore: -------------------------------------------------------------------------------- 1 | obj/ 2 | bin/ 3 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Search/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Search/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Google.Apis.YouTube.Samples.Search")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Google.Apis.YouTube.Samples.Search")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("d3824eb3-21c1-4ded-a0bc-7f95bb898e04")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Search/Search.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | using System; 19 | using System.Collections.Generic; 20 | using System.IO; 21 | using System.Reflection; 22 | using System.Threading; 23 | using System.Threading.Tasks; 24 | 25 | using Google.Apis.Auth.OAuth2; 26 | using Google.Apis.Services; 27 | using Google.Apis.Upload; 28 | using Google.Apis.Util.Store; 29 | using Google.Apis.YouTube.v3; 30 | using Google.Apis.YouTube.v3.Data; 31 | 32 | namespace Google.Apis.YouTube.Samples 33 | { 34 | /// 35 | /// YouTube Data API v3 sample: search by keyword. 36 | /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. 37 | /// See https://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted 38 | /// 39 | /// Set ApiKey to the API key value from the APIs & auth > Registered apps tab of 40 | /// https://cloud.google.com/console 41 | /// Please ensure that you have enabled the YouTube Data API for your project. 42 | /// 43 | internal class Search 44 | { 45 | [STAThread] 46 | static void Main(string[] args) 47 | { 48 | Console.WriteLine("YouTube Data API: Search"); 49 | Console.WriteLine("========================"); 50 | 51 | try 52 | { 53 | new Search().Run().Wait(); 54 | } 55 | catch (AggregateException ex) 56 | { 57 | foreach (var e in ex.InnerExceptions) 58 | { 59 | Console.WriteLine("Error: " + e.Message); 60 | } 61 | } 62 | 63 | Console.WriteLine("Press any key to continue..."); 64 | Console.ReadKey(); 65 | } 66 | 67 | private async Task Run() 68 | { 69 | var youtubeService = new YouTubeService(new BaseClientService.Initializer() 70 | { 71 | ApiKey = "REPLACE_ME", 72 | ApplicationName = this.GetType().ToString() 73 | }); 74 | 75 | var searchListRequest = youtubeService.Search.List("snippet"); 76 | searchListRequest.Q = "Google"; // Replace with your search term. 77 | searchListRequest.MaxResults = 50; 78 | 79 | // Call the search.list method to retrieve results matching the specified query term. 80 | var searchListResponse = await searchListRequest.ExecuteAsync(); 81 | 82 | List videos = new List(); 83 | List channels = new List(); 84 | List playlists = new List(); 85 | 86 | // Add each result to the appropriate list, and then display the lists of 87 | // matching videos, channels, and playlists. 88 | foreach (var searchResult in searchListResponse.Items) 89 | { 90 | switch (searchResult.Id.Kind) 91 | { 92 | case "youtube#video": 93 | videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId)); 94 | break; 95 | 96 | case "youtube#channel": 97 | channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId)); 98 | break; 99 | 100 | case "youtube#playlist": 101 | playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId)); 102 | break; 103 | } 104 | } 105 | 106 | Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos))); 107 | Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels))); 108 | Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists))); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Search/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Upload/.gitignore: -------------------------------------------------------------------------------- 1 | obj/ 2 | bin/ 3 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Upload/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Upload/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Google.Apis.YouTube.Samples.Upload")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Google.Apis.YouTube.Samples.Upload")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("2cc197b6-657d-4397-b330-5d5c8b1442e6")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.Upload/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /dotnet/Google.Apis.YouTube.Samples.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Apis.YouTube.Samples.Playlists", "Google.Apis.YouTube.Samples.Playlists\Google.Apis.YouTube.Samples.Playlists.csproj", "{5781C0CB-169B-42BE-A7D2-766520F3CCD0}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Apis.YouTube.Samples.Search", "Google.Apis.YouTube.Samples.Search\Google.Apis.YouTube.Samples.Search.csproj", "{1DB7F593-3C99-4171-A584-5234457E7351}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Google.Apis.YouTube.Samples.Upload", "Google.Apis.YouTube.Samples.Upload\Google.Apis.YouTube.Samples.Upload.csproj", "{19C80AA8-950B-4182-940F-760EFE9D32BB}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {5781C0CB-169B-42BE-A7D2-766520F3CCD0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {5781C0CB-169B-42BE-A7D2-766520F3CCD0}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {5781C0CB-169B-42BE-A7D2-766520F3CCD0}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {5781C0CB-169B-42BE-A7D2-766520F3CCD0}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {1DB7F593-3C99-4171-A584-5234457E7351}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {1DB7F593-3C99-4171-A584-5234457E7351}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {1DB7F593-3C99-4171-A584-5234457E7351}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {1DB7F593-3C99-4171-A584-5234457E7351}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {19C80AA8-950B-4182-940F-760EFE9D32BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {19C80AA8-950B-4182-940F-760EFE9D32BB}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {19C80AA8-950B-4182-940F-760EFE9D32BB}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {19C80AA8-950B-4182-940F-760EFE9D32BB}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | EndGlobal 35 | -------------------------------------------------------------------------------- /dotnet/MyUploads.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | using Google.Apis.Auth.OAuth2; 8 | using Google.Apis.Services; 9 | using Google.Apis.Upload; 10 | using Google.Apis.Util.Store; 11 | using Google.Apis.YouTube.v3; 12 | using Google.Apis.YouTube.v3.Data; 13 | 14 | namespace Google.Apis.YouTube.Samples 15 | { 16 | /// 17 | /// YouTube Data API v3 sample: retrieve my uploads. 18 | /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. 19 | /// See https://developers.google.com/api-client-library/dotnet/get_started 20 | /// 21 | internal class MyUploads 22 | { 23 | [STAThread] 24 | static void Main(string[] args) 25 | { 26 | Console.WriteLine("YouTube Data API: My Uploads"); 27 | Console.WriteLine("============================"); 28 | 29 | try 30 | { 31 | new MyUploads().Run().Wait(); 32 | } 33 | catch (AggregateException ex) 34 | { 35 | foreach (var e in ex.InnerExceptions) 36 | { 37 | Console.WriteLine("Error: " + e.Message); 38 | } 39 | } 40 | 41 | Console.WriteLine("Press any key to continue..."); 42 | Console.ReadKey(); 43 | } 44 | 45 | private async Task Run() 46 | { 47 | UserCredential credential; 48 | using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 49 | { 50 | credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( 51 | GoogleClientSecrets.Load(stream).Secrets, 52 | // This OAuth 2.0 access scope allows for read-only access to the authenticated 53 | // user's account, but not other types of account access. 54 | new[] { YouTubeService.Scope.YoutubeReadonly }, 55 | "user", 56 | CancellationToken.None, 57 | new FileDataStore(this.GetType().ToString()) 58 | ); 59 | } 60 | 61 | var youtubeService = new YouTubeService(new BaseClientService.Initializer() 62 | { 63 | HttpClientInitializer = credential, 64 | ApplicationName = this.GetType().ToString() 65 | }); 66 | 67 | var channelsListRequest = youtubeService.Channels.List("contentDetails"); 68 | channelsListRequest.Mine = true; 69 | 70 | // Retrieve the contentDetails part of the channel resource for the authenticated user's channel. 71 | var channelsListResponse = await channelsListRequest.ExecuteAsync(); 72 | 73 | foreach (var channel in channelsListResponse.Items) 74 | { 75 | // From the API response, extract the playlist ID that identifies the list 76 | // of videos uploaded to the authenticated user's channel. 77 | var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads; 78 | 79 | Console.WriteLine("Videos in list {0}", uploadsListId); 80 | 81 | var nextPageToken = ""; 82 | while (nextPageToken != null) 83 | { 84 | var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet"); 85 | playlistItemsListRequest.PlaylistId = uploadsListId; 86 | playlistItemsListRequest.MaxResults = 50; 87 | playlistItemsListRequest.PageToken = nextPageToken; 88 | 89 | // Retrieve the list of videos uploaded to the authenticated user's channel. 90 | var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync(); 91 | 92 | foreach (var playlistItem in playlistItemsListResponse.Items) 93 | { 94 | // Print information about each video. 95 | Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId); 96 | } 97 | 98 | nextPageToken = playlistItemsListResponse.NextPageToken; 99 | } 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /dotnet/PlaylistUpdates.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | using Google.Apis.Auth.OAuth2; 8 | using Google.Apis.Services; 9 | using Google.Apis.Upload; 10 | using Google.Apis.Util.Store; 11 | using Google.Apis.YouTube.v3; 12 | using Google.Apis.YouTube.v3.Data; 13 | 14 | namespace Google.Apis.YouTube.Samples 15 | { 16 | /// 17 | /// YouTube Data API v3 sample: create a playlist. 18 | /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. 19 | /// See https://developers.google.com/api-client-library/dotnet/get_started 20 | /// 21 | internal class PlaylistUpdates 22 | { 23 | [STAThread] 24 | static void Main(string[] args) 25 | { 26 | Console.WriteLine("YouTube Data API: Playlist Updates"); 27 | Console.WriteLine("=================================="); 28 | 29 | try 30 | { 31 | new PlaylistUpdates().Run().Wait(); 32 | } 33 | catch (AggregateException ex) 34 | { 35 | foreach (var e in ex.InnerExceptions) 36 | { 37 | Console.WriteLine("Error: " + e.Message); 38 | } 39 | } 40 | 41 | Console.WriteLine("Press any key to continue..."); 42 | Console.ReadKey(); 43 | } 44 | 45 | private async Task Run() 46 | { 47 | UserCredential credential; 48 | using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 49 | { 50 | credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( 51 | GoogleClientSecrets.Load(stream).Secrets, 52 | // This OAuth 2.0 access scope allows for full read/write access to the 53 | // authenticated user's account. 54 | new[] { YouTubeService.Scope.Youtube }, 55 | "user", 56 | CancellationToken.None, 57 | new FileDataStore(this.GetType().ToString()) 58 | ); 59 | } 60 | 61 | var youtubeService = new YouTubeService(new BaseClientService.Initializer() 62 | { 63 | HttpClientInitializer = credential, 64 | ApplicationName = this.GetType().ToString() 65 | }); 66 | 67 | // Create a new, private playlist in the authorized user's channel. 68 | var newPlaylist = new Playlist(); 69 | newPlaylist.Snippet = new PlaylistSnippet(); 70 | newPlaylist.Snippet.Title = "Test Playlist"; 71 | newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3"; 72 | newPlaylist.Status = new PlaylistStatus(); 73 | newPlaylist.Status.PrivacyStatus = "public"; 74 | newPlaylist = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync(); 75 | 76 | // Add a video to the newly created playlist. 77 | var newPlaylistItem = new PlaylistItem(); 78 | newPlaylistItem.Snippet = new PlaylistItemSnippet(); 79 | newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id; 80 | newPlaylistItem.Snippet.ResourceId = new ResourceId(); 81 | newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"; 82 | newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI"; 83 | newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync(); 84 | 85 | Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /dotnet/README.md: -------------------------------------------------------------------------------- 1 | ## Samples in this directory: 2 | 3 | ### [Create a playlist](/dotnet/PlaylistUpdates.cs) 4 | 5 | Method: youtube.playlists.insert
6 | Description: The following code sample calls the API's playlists.insert method to create a private playlist 7 | owned by the channel authorizing the request. 8 | 9 | ### [Retrieve my uploads](/dotnet/MyUploads.cs) 10 | 11 | Method: youtube.playlistItems.list
12 | Description: The following code sample calls the API's playlistItems.list method to retrieve a list of videos 13 | uploaded to the channel associated with the request. The code also calls the channels.list method with the 14 | mine parameter set to true to retrieve the playlist ID that identifies the channel's uploaded 15 | videos. 16 | 17 | ### [Search by keyword](/dotnet/Search.cs) 18 | 19 | Method: youtube.search.list
20 | Description: The following code sample calls the API's search.list method to retrieve search results 21 | associated with a particular keyword. 22 | 23 | ### [Upload a video](/dotnet/UploadVideo.cs) 24 | 25 | Method: youtube.videos.insert
26 | Description: The following code sample calls the API's videos.insert method to upload a video to the channel 27 | associated with the request. 28 | -------------------------------------------------------------------------------- /dotnet/Search.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Reflection; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | using Google.Apis.Auth.OAuth2; 9 | using Google.Apis.Services; 10 | using Google.Apis.Upload; 11 | using Google.Apis.Util.Store; 12 | using Google.Apis.YouTube.v3; 13 | using Google.Apis.YouTube.v3.Data; 14 | 15 | namespace Google.Apis.YouTube.Samples 16 | { 17 | /// 18 | /// YouTube Data API v3 sample: search by keyword. 19 | /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. 20 | /// See https://developers.google.com/api-client-library/dotnet/get_started 21 | /// 22 | /// Set ApiKey to the API key value from the APIs & auth > Registered apps tab of 23 | /// https://cloud.google.com/console 24 | /// Please ensure that you have enabled the YouTube Data API for your project. 25 | /// 26 | internal class Search 27 | { 28 | [STAThread] 29 | static void Main(string[] args) 30 | { 31 | Console.WriteLine("YouTube Data API: Search"); 32 | Console.WriteLine("========================"); 33 | 34 | try 35 | { 36 | new Search().Run().Wait(); 37 | } 38 | catch (AggregateException ex) 39 | { 40 | foreach (var e in ex.InnerExceptions) 41 | { 42 | Console.WriteLine("Error: " + e.Message); 43 | } 44 | } 45 | 46 | Console.WriteLine("Press any key to continue..."); 47 | Console.ReadKey(); 48 | } 49 | 50 | private async Task Run() 51 | { 52 | var youtubeService = new YouTubeService(new BaseClientService.Initializer() 53 | { 54 | ApiKey = "REPLACE_ME", 55 | ApplicationName = this.GetType().ToString() 56 | }); 57 | 58 | var searchListRequest = youtubeService.Search.List("snippet"); 59 | searchListRequest.Q = "Google"; // Replace with your search term. 60 | searchListRequest.MaxResults = 50; 61 | 62 | // Call the search.list method to retrieve results matching the specified query term. 63 | var searchListResponse = await searchListRequest.ExecuteAsync(); 64 | 65 | List videos = new List(); 66 | List channels = new List(); 67 | List playlists = new List(); 68 | 69 | // Add each result to the appropriate list, and then display the lists of 70 | // matching videos, channels, and playlists. 71 | foreach (var searchResult in searchListResponse.Items) 72 | { 73 | switch (searchResult.Id.Kind) 74 | { 75 | case "youtube#video": 76 | videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId)); 77 | break; 78 | 79 | case "youtube#channel": 80 | channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId)); 81 | break; 82 | 83 | case "youtube#playlist": 84 | playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId)); 85 | break; 86 | } 87 | } 88 | 89 | Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos))); 90 | Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels))); 91 | Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists))); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /dotnet/UploadVideo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | using Google.Apis.Auth.OAuth2; 8 | using Google.Apis.Services; 9 | using Google.Apis.Upload; 10 | using Google.Apis.Util.Store; 11 | using Google.Apis.YouTube.v3; 12 | using Google.Apis.YouTube.v3.Data; 13 | 14 | namespace Google.Apis.YouTube.Samples 15 | { 16 | /// 17 | /// YouTube Data API v3 sample: upload a video. 18 | /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. 19 | /// See https://developers.google.com/api-client-library/dotnet/get_started 20 | /// 21 | internal class UploadVideo 22 | { 23 | [STAThread] 24 | static void Main(string[] args) 25 | { 26 | Console.WriteLine("YouTube Data API: Upload Video"); 27 | Console.WriteLine("=============================="); 28 | 29 | try 30 | { 31 | new UploadVideo().Run().Wait(); 32 | } 33 | catch (AggregateException ex) 34 | { 35 | foreach (var e in ex.InnerExceptions) 36 | { 37 | Console.WriteLine("Error: " + e.Message); 38 | } 39 | } 40 | 41 | Console.WriteLine("Press any key to continue..."); 42 | Console.ReadKey(); 43 | } 44 | 45 | private async Task Run() 46 | { 47 | UserCredential credential; 48 | using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) 49 | { 50 | credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( 51 | GoogleClientSecrets.Load(stream).Secrets, 52 | // This OAuth 2.0 access scope allows an application to upload files to the 53 | // authenticated user's YouTube channel, but doesn't allow other types of access. 54 | new[] { YouTubeService.Scope.YoutubeUpload }, 55 | "user", 56 | CancellationToken.None 57 | ); 58 | } 59 | 60 | var youtubeService = new YouTubeService(new BaseClientService.Initializer() 61 | { 62 | HttpClientInitializer = credential, 63 | ApplicationName = Assembly.GetExecutingAssembly().GetName().Name 64 | }); 65 | 66 | var video = new Video(); 67 | video.Snippet = new VideoSnippet(); 68 | video.Snippet.Title = "Default Video Title"; 69 | video.Snippet.Description = "Default Video Description"; 70 | video.Snippet.Tags = new string[] { "tag1", "tag2" }; 71 | video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list 72 | video.Status = new VideoStatus(); 73 | video.Status.PrivacyStatus = "unlisted"; // or "private" or "public" 74 | var filePath = @"REPLACE_ME.mp4"; // Replace with path to actual movie file. 75 | 76 | using (var fileStream = new FileStream(filePath, FileMode.Open)) 77 | { 78 | var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*"); 79 | videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged; 80 | videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived; 81 | 82 | await videosInsertRequest.UploadAsync(); 83 | } 84 | } 85 | 86 | void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress) 87 | { 88 | switch (progress.Status) 89 | { 90 | case UploadStatus.Uploading: 91 | Console.WriteLine("{0} bytes sent.", progress.BytesSent); 92 | break; 93 | 94 | case UploadStatus.Failed: 95 | Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception); 96 | break; 97 | } 98 | } 99 | 100 | void videosInsertRequest_ResponseReceived(Video video) 101 | { 102 | Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /dotnet/client_secrets.json: -------------------------------------------------------------------------------- 1 | { 2 | installed : { 3 | "client_id": "YOUR_CLIENT_ID", 4 | "client_secret": "YOUR_CLIENT_SECRET", 5 | "redirect_uri" : "urn:ietf:wg:oauth:2.0:oob" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /dotnet/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /dotnet/packages/repositories.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /go/README.md: -------------------------------------------------------------------------------- 1 | Recommended Go version: latest version 2 | 3 | To run these code samples, you will need to install the dependent libraries via 4 | the "go get" command. See the client library's getting started guide for more detail: 5 | https://github.com/google/google-api-go-client/blob/master/GettingStarted.md 6 | 7 | You also need to enable the YouTube Data API for the project associated with your developer 8 | credentials. 9 | 10 | ## Authorization credentials 11 | To run any sample that does not require user authorization, such as search\_by\_keyword.go, 12 | you need to replace the value of the `developerKey` constant with a valid API key: 13 | 14 | ``` 15 | const developerKey = "YOUR DEVELOPER KEY" 16 | ``` 17 | 18 | To run any sample that requires authorization on behalf of a user, such as retrieving the 19 | authenticated user's uploads, you need an OAuth 2.0 client ID and client secret pair. These 20 | can be created at the Google API console at https://developers.google.com/console. After 21 | creating your OAuth 2.0 credentials, download the client\_secret.json file to the directory 22 | in which you are running these samples. 23 | 24 | ## Running samples 25 | 26 | Samples can be run with the standard "go run" command as long as your API key or OAuth 2.0 27 | credentials are in place. The samples use the `errors.go` file to 28 | print out API errors, so you need to also include that file in the "go run" command. Samples 29 | that require authorization also require the `oauth2.go` file to be included in the 30 | "go run" command: 31 | 32 | Example usages: 33 | 34 | ``` 35 |   go run search_by_keyword.go errors.go 36 | go run my_uploads.go errors.go oauth2.go 37 | go run upload_video.go errors.go oauth2.go --filename="sample_video.flv" --title="Test video" --keywords="golang test" 38 | ``` 39 | 40 | More information about the YouTube APIs can be found at https://developers.google.com/youtube. 41 | 42 | ## Samples in this directory: 43 | 44 | ### [Authorize a request](/go/oauth2.go) 45 | 46 | Description: This code sample performs OAuth 2.0 authorization by checking for the presence of a local file that 47 | contains authorization credentials. If the file is not present, the script opens a browser and waits for a response, 48 | then saves the returned credentials locally. 49 | 50 | ### [List playlists](/go/playlists.go) 51 | 52 | Methods: youtube.playlists.list
53 | Description: This code sample calls the API's `playlists.list` method. Use command-line flags to define the parameters you want to use in the request as shown in the following examples:

54 | 55 | ``` 56 | # Retrieve playlists for a specified channel 57 | go run playlists.go oauth.go errors.go --channelId=UC_x5XG1OV2P6uZZ5FSM9Ttw 58 | 59 | # Retrieve authenticated user's playlists 60 | go run playlists.go oauth.go errors.go --mine=true 61 | ``` 62 | 63 | ### [Retrieve my uploads](/go/my_uploads.go) 64 | 65 | Methods: youtube.channels.list, youtube.playlistItems.list
66 | Description: This code sample calls the API's playlistItems.list method to retrieve a list of 67 | videos uploaded to the channel associated with the request. The code also calls the channels.list 68 | method with the mine parameter set to true to retrieve the playlist ID that identifies 69 | the channel's uploaded videos. 70 | 71 | ### [Search by keyword](/go/search_by_keyword.go) 72 | 73 | Method: youtube.search.list
74 | Description: This code sample calls the API's search.list method to retrieve search results associated 75 | with a particular keyword. 76 | 77 | ### [Upload a video](/go/upload_video.go) 78 | 79 | Method: youtube.videos.insert
80 | Description: This code sample calls the API's videos.insert method to upload a video to the channel 81 | associated with the request. 82 | -------------------------------------------------------------------------------- /go/client_secrets.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "installed": { 3 | "client_id": "YOUR_CLIENT_ID_HERE", 4 | "client_secret": "YOUR_CLIENT_SECRET_HERE", 5 | "redirect_uris": ["http://localhost:8080/oauth2callback"], 6 | "auth_uri": "https://accounts.google.com/o/oauth2/auth", 7 | "token_uri": "https://accounts.google.com/o/oauth2/token" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /go/errors.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | ) 6 | 7 | func handleError(err error, message string) { 8 | if message == "" { 9 | message = "Error making API call" 10 | } 11 | if err != nil { 12 | log.Fatalf(message + ": %v", err.Error()) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /go/my_uploads.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "google.golang.org/api/youtube/v3" 8 | ) 9 | 10 | // Retrieve playlistItems in the specified playlist 11 | func playlistItemsList(service *youtube.Service, part string, playlistId string, pageToken string) *youtube.PlaylistItemListResponse { 12 | call := service.PlaylistItems.List(part) 13 | call = call.PlaylistId(playlistId) 14 | if pageToken != "" { 15 | call = call.PageToken(pageToken) 16 | } 17 | response, err := call.Do() 18 | handleError(err, "") 19 | return response 20 | } 21 | 22 | // Retrieve resource for the authenticated user's channel 23 | func channelsListMine(service *youtube.Service, part string) *youtube.ChannelListResponse { 24 | call := service.Channels.List(part) 25 | call = call.Mine(true) 26 | response, err := call.Do() 27 | handleError(err, "") 28 | return response 29 | } 30 | 31 | func main() { 32 | client := getClient(youtube.YoutubeReadonlyScope) 33 | service, err := youtube.New(client) 34 | 35 | if err != nil { 36 | log.Fatalf("Error creating YouTube client: %v", err) 37 | } 38 | 39 | response := channelsListMine(service, "contentDetails") 40 | 41 | for _, channel := range response.Items { 42 | playlistId := channel.ContentDetails.RelatedPlaylists.Uploads 43 | 44 | // Print the playlist ID for the list of uploaded videos. 45 | fmt.Printf("Videos in list %s\r\n", playlistId) 46 | 47 | nextPageToken := "" 48 | for { 49 | // Retrieve next set of items in the playlist. 50 | playlistResponse := playlistItemsList(service, "snippet", playlistId, nextPageToken) 51 | 52 | for _, playlistItem := range playlistResponse.Items { 53 | title := playlistItem.Snippet.Title 54 | videoId := playlistItem.Snippet.ResourceId.VideoId 55 | fmt.Printf("%v, (%v)\r\n", title, videoId) 56 | } 57 | 58 | // Set the token to retrieve the next page of results 59 | // or exit the loop if all results have been retrieved. 60 | nextPageToken = playlistResponse.NextPageToken 61 | if nextPageToken == "" { 62 | break 63 | } 64 | fmt.Println() 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /go/playlists.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | 8 | "google.golang.org/api/youtube/v3" 9 | ) 10 | 11 | var ( 12 | method = flag.String("method", "list", "The API method to execute. (List is the only method that this sample currently supports.") 13 | 14 | channelId = flag.String("channelId", "", "Retrieve playlists for this channel. Value is a YouTube channel ID.") 15 | hl = flag.String("hl", "", "Retrieve localized resource metadata for the specified application language.") 16 | maxResults = flag.Int64("maxResults", 5, "The maximum number of playlist resources to include in the API response.") 17 | mine = flag.Bool("mine", false, "List playlists for authenticated user's channel. Default: false.") 18 | onBehalfOfContentOwner = flag.String("onBehalfOfContentOwner", "", "Indicates that the request's auth credentials identify a user authorized to act on behalf of the specified content owner.") 19 | pageToken = flag.String("pageToken", "", "Token that identifies a specific page in the result set that should be returned.") 20 | part = flag.String("part", "snippet", "Comma-separated list of playlist resource parts that API response will include.") 21 | playlistId = flag.String("playlistId", "", "Retrieve information about this playlist.") 22 | ) 23 | 24 | func playlistsList(service *youtube.Service, part string, channelId string, hl string, maxResults int64, mine bool, onBehalfOfContentOwner string, pageToken string, playlistId string) *youtube.PlaylistListResponse { 25 | call := service.Playlists.List(part) 26 | if channelId != "" { 27 | call = call.ChannelId(channelId) 28 | } 29 | if hl != "" { 30 | call = call.Hl(hl) 31 | } 32 | call = call.MaxResults(maxResults) 33 | if mine != false { 34 | call = call.Mine(true) 35 | } 36 | if onBehalfOfContentOwner != "" { 37 | call = call.OnBehalfOfContentOwner(onBehalfOfContentOwner) 38 | } 39 | if pageToken != "" { 40 | call = call.PageToken(pageToken) 41 | } 42 | if playlistId != "" { 43 | call = call.Id(playlistId) 44 | } 45 | response, err := call.Do() 46 | handleError(err, "") 47 | return response 48 | } 49 | 50 | func main() { 51 | flag.Parse() 52 | 53 | if *channelId == "" && *mine == false && *playlistId == "" { 54 | log.Fatalf("You must either set a value for the channelId or playlistId flag or set the mine flag to 'true'.") 55 | } 56 | client := getClient(youtube.YoutubeReadonlyScope) 57 | 58 | service, err := youtube.New(client) 59 | if err != nil { 60 | log.Fatalf("Error creating YouTube client: %v", err) 61 | } 62 | 63 | response := playlistsList(service, "snippet,contentDetails", *channelId, *hl, *maxResults, *mine, *onBehalfOfContentOwner, *pageToken, *playlistId) 64 | 65 | for _, playlist := range response.Items { 66 | playlistId := playlist.Id 67 | playlistTitle := playlist.Snippet.Title 68 | 69 | // Print the playlist ID and title for the playlist resource. 70 | fmt.Println(playlistId, ": ", playlistTitle) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /go/search_by_keyword.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | 9 | "google.golang.org/api/googleapi/transport" 10 | "google.golang.org/api/youtube/v3" 11 | ) 12 | 13 | var ( 14 | query = flag.String("query", "Google", "Search term") 15 | maxResults = flag.Int64("max-results", 25, "Max YouTube results") 16 | ) 17 | 18 | const developerKey = "YOUR DEVELOPER KEY" 19 | 20 | func main() { 21 | flag.Parse() 22 | 23 | client := &http.Client{ 24 | Transport: &transport.APIKey{Key: developerKey}, 25 | } 26 | 27 | service, err := youtube.New(client) 28 | if err != nil { 29 | log.Fatalf("Error creating new YouTube client: %v", err) 30 | } 31 | 32 | // Make the API call to YouTube. 33 | call := service.Search.List("id,snippet"). 34 | Q(*query). 35 | MaxResults(*maxResults) 36 | response, err := call.Do() 37 | handleError(err, "") 38 | 39 | // Group video, channel, and playlist results in separate lists. 40 | videos := make(map[string]string) 41 | channels := make(map[string]string) 42 | playlists := make(map[string]string) 43 | 44 | // Iterate through each item and add it to the correct list. 45 | for _, item := range response.Items { 46 | switch item.Id.Kind { 47 | case "youtube#video": 48 | videos[item.Id.VideoId] = item.Snippet.Title 49 | case "youtube#channel": 50 | channels[item.Id.ChannelId] = item.Snippet.Title 51 | case "youtube#playlist": 52 | playlists[item.Id.PlaylistId] = item.Snippet.Title 53 | } 54 | } 55 | 56 | printIDs("Videos", videos) 57 | printIDs("Channels", channels) 58 | printIDs("Playlists", playlists) 59 | } 60 | 61 | // Print the ID and title of each result in a list as well as a name that 62 | // identifies the list. For example, print the word section name "Videos" 63 | // above a list of video search results, followed by the video ID and title 64 | // of each matching video. 65 | func printIDs(sectionName string, matches map[string]string) { 66 | fmt.Printf("%v:\n", sectionName) 67 | for id, title := range matches { 68 | fmt.Printf("[%v] %v\n", id, title) 69 | } 70 | fmt.Printf("\n\n") 71 | } 72 | -------------------------------------------------------------------------------- /go/upload_video.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | 10 | "google.golang.org/api/youtube/v3" 11 | ) 12 | 13 | var ( 14 | filename = flag.String("filename", "", "Name of video file to upload") 15 | title = flag.String("title", "Test Title", "Video title") 16 | description = flag.String("description", "Test Description", "Video description") 17 | category = flag.String("category", "22", "Video category") 18 | keywords = flag.String("keywords", "", "Comma separated list of video keywords") 19 | privacy = flag.String("privacy", "unlisted", "Video privacy status") 20 | ) 21 | 22 | func main() { 23 | flag.Parse() 24 | 25 | if *filename == "" { 26 | log.Fatalf("You must provide a filename of a video file to upload") 27 | } 28 | 29 | client := getClient(youtube.YoutubeUploadScope) 30 | 31 | service, err := youtube.New(client) 32 | if err != nil { 33 | log.Fatalf("Error creating YouTube client: %v", err) 34 | } 35 | 36 | upload := &youtube.Video{ 37 | Snippet: &youtube.VideoSnippet{ 38 | Title: *title, 39 | Description: *description, 40 | CategoryId: *category, 41 | }, 42 | Status: &youtube.VideoStatus{PrivacyStatus: *privacy}, 43 | } 44 | 45 | // The API returns a 400 Bad Request response if tags is an empty string. 46 | if strings.Trim(*keywords, "") != "" { 47 | upload.Snippet.Tags = strings.Split(*keywords, ",") 48 | } 49 | 50 | call := service.Videos.Insert("snippet,status", upload) 51 | 52 | file, err := os.Open(*filename) 53 | defer file.Close() 54 | if err != nil { 55 | log.Fatalf("Error opening %v: %v", *filename, err) 56 | } 57 | 58 | response, err := call.Media(file).Do() 59 | handleError(err, "") 60 | fmt.Printf("Upload successful! Video ID: %v\n", response.Id) 61 | } 62 | -------------------------------------------------------------------------------- /java/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.google.api.services.samples.youtube.cmdline 6 | samples 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | youtube-api-cmdline-samples 11 | http://maven.apache.org 12 | 13 | 14 | v3-rev182-1.22.0 15 | v1-rev63-1.22.0 16 | v1-rev10-1.22.0 17 | 1.20.0 18 | 1.20.0 19 | UTF-8 20 | 21 | 22 | 23 | 24 | google-api-services 25 | http://google-api-client-libraries.appspot.com/mavenrepo 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | com.google.apis 34 | google-api-services-youtube 35 | ${project.youtube.version} 36 | 37 | 38 | 39 | 40 | com.google.apis 41 | google-api-services-youtubeAnalytics 42 | ${project.youtube.analytics.version} 43 | 44 | 45 | 46 | 47 | com.google.apis 48 | google-api-services-youtubereporting 49 | ${project.youtube.reporting.version} 50 | 51 | 52 | 53 | 54 | org.codehaus.jackson 55 | jackson-mapper-asl 56 | 1.9.4 57 | 58 | 59 | 60 | com.google.http-client 61 | google-http-client-jackson2 62 | ${project.http.version} 63 | 64 | 65 | 66 | com.google.oauth-client 67 | google-oauth-client-jetty 68 | ${project.oauth.version} 69 | 70 | 71 | 72 | com.google.collections 73 | google-collections 74 | 1.0 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | maven-compiler-plugin 84 | 3.6.0 85 | 86 | 1.6 87 | 1.6 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /java/src/main/java/com/google/api/services/samples/youtube/cmdline/Auth.java: -------------------------------------------------------------------------------- 1 | package com.google.api.services.samples.youtube.cmdline; 2 | 3 | import com.google.api.client.auth.oauth2.Credential; 4 | import com.google.api.client.auth.oauth2.StoredCredential; 5 | import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; 6 | import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; 7 | import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; 8 | import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; 9 | import com.google.api.client.http.HttpTransport; 10 | import com.google.api.client.http.javanet.NetHttpTransport; 11 | import com.google.api.client.json.JsonFactory; 12 | import com.google.api.client.json.jackson2.JacksonFactory; 13 | import com.google.api.client.util.store.DataStore; 14 | import com.google.api.client.util.store.FileDataStoreFactory; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.io.InputStreamReader; 19 | import java.io.Reader; 20 | import java.util.List; 21 | 22 | /** 23 | * Shared class used by every sample. Contains methods for authorizing a user and caching credentials. 24 | */ 25 | public class Auth { 26 | 27 | /** 28 | * Define a global instance of the HTTP transport. 29 | */ 30 | public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); 31 | 32 | /** 33 | * Define a global instance of the JSON factory. 34 | */ 35 | public static final JsonFactory JSON_FACTORY = new JacksonFactory(); 36 | 37 | /** 38 | * This is the directory that will be used under the user's home directory where OAuth tokens will be stored. 39 | */ 40 | private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials"; 41 | 42 | /** 43 | * Authorizes the installed application to access user's protected data. 44 | * 45 | * @param scopes list of scopes needed to run youtube upload. 46 | * @param credentialDatastore name of the credential datastore to cache OAuth tokens 47 | */ 48 | public static Credential authorize(List scopes, String credentialDatastore) throws IOException { 49 | 50 | // Load client secrets. 51 | Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json")); 52 | GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader); 53 | 54 | // Checks that the defaults have been replaced (Default = "Enter X here"). 55 | if (clientSecrets.getDetails().getClientId().startsWith("Enter") 56 | || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { 57 | System.out.println( 58 | "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential " 59 | + "into src/main/resources/client_secrets.json"); 60 | System.exit(1); 61 | } 62 | 63 | // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore} 64 | FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY)); 65 | DataStore datastore = fileDataStoreFactory.getDataStore(credentialDatastore); 66 | 67 | GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( 68 | HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore) 69 | .build(); 70 | 71 | // Build the local server and bind it to port 8080 72 | LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); 73 | 74 | // Authorize. 75 | return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /java/src/main/java/com/google/api/services/samples/youtube/cmdline/live/DeleteLiveChatMessage.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2017 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.google.api.services.samples.youtube.cmdline.live; 16 | 17 | import com.google.api.client.auth.oauth2.Credential; 18 | import com.google.api.client.googleapis.json.GoogleJsonResponseException; 19 | import com.google.api.services.samples.youtube.cmdline.Auth; 20 | import com.google.api.services.youtube.YouTube; 21 | import com.google.api.services.youtube.YouTubeScopes; 22 | import com.google.common.collect.Lists; 23 | import java.io.IOException; 24 | import java.util.List; 25 | 26 | /** 27 | * Delets a message from a live broadcast, using OAuth 2.0 to authorize API requests. 28 | * 29 | * @author Jim Rogers 30 | */ 31 | public class DeleteLiveChatMessage { 32 | 33 | /** 34 | * Define a global instance of a Youtube object, which will be used 35 | * to make YouTube Data API requests. 36 | */ 37 | private static YouTube youtube; 38 | 39 | /** 40 | * Deletes a message from a live broadcast. 41 | * 42 | * @param args The message id to delete (required) followed by the videoId (optional). If the 43 | * videoId is given, live chat messages will be retrieved from the chat associated with this 44 | * video. If the videoId is not specified, the signed in user's current live broadcast will be 45 | * used instead. 46 | */ 47 | public static void main(String[] args) { 48 | // Get the message id to delete 49 | if (args.length == 0) { 50 | System.err.println("No message id specified"); 51 | System.exit(1); 52 | } 53 | String messageId = args[0]; 54 | 55 | // This OAuth 2.0 access scope allows for write access to the authenticated user's account. 56 | List scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_FORCE_SSL); 57 | 58 | try { 59 | // Authorize the request. 60 | Credential credential = Auth.authorize(scopes, "deletelivechatmessage"); 61 | 62 | // This object is used to make YouTube Data API requests. 63 | youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) 64 | .setApplicationName("youtube-cmdline-deletechatmessages-sample").build(); 65 | 66 | // Delete the message from live chat 67 | YouTube.LiveChatMessages.Delete liveChatDelete = 68 | youtube.liveChatMessages().delete(messageId); 69 | liveChatDelete.execute(); 70 | System.out.println("Deleted message id " + messageId); 71 | } catch (GoogleJsonResponseException e) { 72 | System.err 73 | .println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " 74 | + e.getDetails().getMessage()); 75 | e.printStackTrace(); 76 | } catch (IOException e) { 77 | System.err.println("IOException: " + e.getMessage()); 78 | e.printStackTrace(); 79 | } catch (Throwable t) { 80 | System.err.println("Throwable: " + t.getMessage()); 81 | t.printStackTrace(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /java/src/main/java/com/google/api/services/samples/youtube/cmdline/live/ListStreams.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2013 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | 15 | package com.google.api.services.samples.youtube.cmdline.live; 16 | 17 | import com.google.api.client.auth.oauth2.Credential; 18 | import com.google.api.client.googleapis.json.GoogleJsonResponseException; 19 | import com.google.api.services.samples.youtube.cmdline.Auth; 20 | import com.google.api.services.youtube.YouTube; 21 | import com.google.api.services.youtube.model.LiveStream; 22 | import com.google.api.services.youtube.model.LiveStreamListResponse; 23 | import com.google.common.collect.Lists; 24 | 25 | import java.io.IOException; 26 | import java.util.List; 27 | 28 | /** 29 | * Retrieve a list of a channel's streams, using OAuth 2.0 to authorize 30 | * API requests. 31 | * 32 | * @author Ibrahim Ulukaya 33 | */ 34 | public class ListStreams { 35 | 36 | /** 37 | * Define a global instance of a Youtube object, which will be used 38 | * to make YouTube Data API requests. 39 | */ 40 | private static YouTube youtube; 41 | 42 | /** 43 | * List streams for the user's channel. 44 | */ 45 | public static void main(String[] args) { 46 | 47 | // This OAuth 2.0 access scope allows for read-only access to the 48 | // authenticated user's account, but not other types of account access. 49 | List scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.readonly"); 50 | 51 | try { 52 | // Authorize the request. 53 | Credential credential = Auth.authorize(scopes, "liststreams"); 54 | 55 | // This object is used to make YouTube Data API requests. 56 | youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) 57 | .setApplicationName("youtube-cmdline-liststreams-sample") 58 | .build(); 59 | 60 | // Create a request to list liveStream resources. 61 | YouTube.LiveStreams.List livestreamRequest = youtube.liveStreams().list("id,snippet"); 62 | 63 | // Modify results to only return the user's streams. 64 | livestreamRequest.setMine(true); 65 | 66 | // Execute the API request and return the list of streams. 67 | LiveStreamListResponse returnedListResponse = livestreamRequest.execute(); 68 | List returnedList = returnedListResponse.getItems(); 69 | 70 | // Print information from the API response. 71 | System.out.println("\n================== Returned Streams ==================\n"); 72 | for (LiveStream stream : returnedList) { 73 | System.out.println(" - Id: " + stream.getId()); 74 | System.out.println(" - Title: " + stream.getSnippet().getTitle()); 75 | System.out.println(" - Description: " + stream.getSnippet().getDescription()); 76 | System.out.println(" - Published At: " + stream.getSnippet().getPublishedAt()); 77 | System.out.println("\n-------------------------------------------------------------\n"); 78 | } 79 | 80 | } catch (GoogleJsonResponseException e) { 81 | System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " 82 | + e.getDetails().getMessage()); 83 | e.printStackTrace(); 84 | 85 | } catch (IOException e) { 86 | System.err.println("IOException: " + e.getMessage()); 87 | e.printStackTrace(); 88 | } catch (Throwable t) { 89 | System.err.println("Throwable: " + t.getMessage()); 90 | t.printStackTrace(); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /java/src/main/resources/client_secrets.json: -------------------------------------------------------------------------------- 1 | { 2 | "installed": { 3 | "client_id": "Enter your client id here", 4 | "client_secret": "Enter your client secret here" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /java/src/main/resources/sample-video.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youtube/api-samples/07263305b59a7c3275bc7e925f9ce6cabf774022/java/src/main/resources/sample-video.mp4 -------------------------------------------------------------------------------- /java/src/main/resources/watermark.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youtube/api-samples/07263305b59a7c3275bc7e925f9ce6cabf774022/java/src/main/resources/watermark.jpg -------------------------------------------------------------------------------- /java/src/main/resources/youtube.properties: -------------------------------------------------------------------------------- 1 | # Replace this with an API key available at 2 | # https://console.developers.google.com/project/_/apiui/credential 3 | youtube.apikey=YOUR_SIMPLE_API_KEY_HERE 4 | -------------------------------------------------------------------------------- /javascript/analytics_codelab.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Helvetica, sans-serif; 3 | } 4 | 5 | .pre-auth { 6 | display: none; 7 | } 8 | 9 | .post-auth { 10 | display: none; 11 | } 12 | 13 | #chart { 14 | width: 500px; 15 | height: 300px; 16 | margin-bottom: 1em; 17 | } 18 | 19 | #video-list { 20 | padding-left: 1em; 21 | list-style-type: none; 22 | } 23 | #video-list > li { 24 | cursor: pointer; 25 | } 26 | #video-list > li:hover { 27 | color: blue; 28 | } 29 | -------------------------------------------------------------------------------- /javascript/analytics_codelab.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Google I/O YouTube Codelab 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
This application requires access to your YouTube account. 13 | Please authorize to continue. 14 |
15 |
16 |
17 |
18 |
Choose a Video:
19 |
    20 |
    21 | 22 | 23 | -------------------------------------------------------------------------------- /javascript/auth.js: -------------------------------------------------------------------------------- 1 | // The client ID is obtained from the {{ Google Cloud Console }} 2 | // at {{ https://cloud.google.com/console }}. 3 | // If you run this code from a server other than http://localhost, 4 | // you need to register your own client ID. 5 | var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__'; 6 | var OAUTH2_SCOPES = [ 7 | 'https://www.googleapis.com/auth/youtube' 8 | ]; 9 | 10 | // Upon loading, the Google APIs JS client automatically invokes this callback. 11 | googleApiClientReady = function() { 12 | gapi.auth.init(function() { 13 | window.setTimeout(checkAuth, 1); 14 | }); 15 | } 16 | 17 | // Attempt the immediate OAuth 2.0 client flow as soon as the page loads. 18 | // If the currently logged-in Google Account has previously authorized 19 | // the client specified as the OAUTH2_CLIENT_ID, then the authorization 20 | // succeeds with no user intervention. Otherwise, it fails and the 21 | // user interface that prompts for authorization needs to display. 22 | function checkAuth() { 23 | gapi.auth.authorize({ 24 | client_id: OAUTH2_CLIENT_ID, 25 | scope: OAUTH2_SCOPES, 26 | immediate: true 27 | }, handleAuthResult); 28 | } 29 | 30 | // Handle the result of a gapi.auth.authorize() call. 31 | function handleAuthResult(authResult) { 32 | if (authResult && !authResult.error) { 33 | // Authorization was successful. Hide authorization prompts and show 34 | // content that should be visible after authorization succeeds. 35 | $('.pre-auth').hide(); 36 | $('.post-auth').show(); 37 | loadAPIClientInterfaces(); 38 | } else { 39 | // Make the #login-link clickable. Attempt a non-immediate OAuth 2.0 40 | // client flow. The current function is called when that flow completes. 41 | $('#login-link').click(function() { 42 | gapi.auth.authorize({ 43 | client_id: OAUTH2_CLIENT_ID, 44 | scope: OAUTH2_SCOPES, 45 | immediate: false 46 | }, handleAuthResult); 47 | }); 48 | } 49 | } 50 | 51 | // Load the client interfaces for the YouTube Analytics and Data APIs, which 52 | // are required to use the Google APIs JS client. More info is available at 53 | // https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api 54 | function loadAPIClientInterfaces() { 55 | gapi.client.load('youtube', 'v3', function() { 56 | handleAPILoaded(); 57 | }); 58 | } 59 | -------------------------------------------------------------------------------- /javascript/my_uploads.css: -------------------------------------------------------------------------------- 1 | .paging-button { 2 | visibility: hidden; 3 | } 4 | 5 | .button-container { 6 | clear: both; 7 | } 8 | -------------------------------------------------------------------------------- /javascript/my_uploads.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | My Uploads 5 | 6 | 7 | 8 |
    9 | This application requires access to your YouTube account. 10 | Please authorize to continue. 11 |
    12 |
    13 |
    14 | 15 | 16 |
    17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /javascript/my_uploads.js: -------------------------------------------------------------------------------- 1 | // Define some variables used to remember state. 2 | var playlistId, nextPageToken, prevPageToken; 3 | 4 | // After the API loads, call a function to get the uploads playlist ID. 5 | function handleAPILoaded() { 6 | requestUserUploadsPlaylistId(); 7 | } 8 | 9 | // Call the Data API to retrieve the playlist ID that uniquely identifies the 10 | // list of videos uploaded to the currently authenticated user's channel. 11 | function requestUserUploadsPlaylistId() { 12 | // See https://developers.google.com/youtube/v3/docs/channels/list 13 | var request = gapi.client.youtube.channels.list({ 14 | mine: true, 15 | part: 'contentDetails' 16 | }); 17 | request.execute(function(response) { 18 | playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads; 19 | requestVideoPlaylist(playlistId); 20 | }); 21 | } 22 | 23 | // Retrieve the list of videos in the specified playlist. 24 | function requestVideoPlaylist(playlistId, pageToken) { 25 | $('#video-container').html(''); 26 | var requestOptions = { 27 | playlistId: playlistId, 28 | part: 'snippet', 29 | maxResults: 10 30 | }; 31 | if (pageToken) { 32 | requestOptions.pageToken = pageToken; 33 | } 34 | var request = gapi.client.youtube.playlistItems.list(requestOptions); 35 | request.execute(function(response) { 36 | // Only show pagination buttons if there is a pagination token for the 37 | // next or previous page of results. 38 | nextPageToken = response.result.nextPageToken; 39 | var nextVis = nextPageToken ? 'visible' : 'hidden'; 40 | $('#next-button').css('visibility', nextVis); 41 | prevPageToken = response.result.prevPageToken 42 | var prevVis = prevPageToken ? 'visible' : 'hidden'; 43 | $('#prev-button').css('visibility', prevVis); 44 | 45 | var playlistItems = response.result.items; 46 | if (playlistItems) { 47 | $.each(playlistItems, function(index, item) { 48 | displayResult(item.snippet); 49 | }); 50 | } else { 51 | $('#video-container').html('Sorry you have no uploaded videos'); 52 | } 53 | }); 54 | } 55 | 56 | // Create a listing for a video. 57 | function displayResult(videoSnippet) { 58 | var title = videoSnippet.title; 59 | var videoId = videoSnippet.resourceId.videoId; 60 | $('#video-container').append('

    ' + title + ' - ' + videoId + '

    '); 61 | } 62 | 63 | // Retrieve the next page of videos in the playlist. 64 | function nextPage() { 65 | requestVideoPlaylist(playlistId, nextPageToken); 66 | } 67 | 68 | // Retrieve the previous page of videos in the playlist. 69 | function previousPage() { 70 | requestVideoPlaylist(playlistId, prevPageToken); 71 | } 72 | -------------------------------------------------------------------------------- /javascript/nodejs-quickstart.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var readline = require('readline'); 3 | var {google} = require('googleapis'); 4 | var OAuth2 = google.auth.OAuth2; 5 | 6 | // If modifying these scopes, delete your previously saved credentials 7 | // at ~/.credentials/youtube-nodejs-quickstart.json 8 | var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']; 9 | var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || 10 | process.env.USERPROFILE) + '/.credentials/'; 11 | var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json'; 12 | 13 | // Load client secrets from a local file. 14 | fs.readFile('client_secret.json', function processClientSecrets(err, content) { 15 | if (err) { 16 | console.log('Error loading client secret file: ' + err); 17 | return; 18 | } 19 | // Authorize a client with the loaded credentials, then call the YouTube API. 20 | authorize(JSON.parse(content), getChannel); 21 | }); 22 | 23 | /** 24 | * Create an OAuth2 client with the given credentials, and then execute the 25 | * given callback function. 26 | * 27 | * @param {Object} credentials The authorization client credentials. 28 | * @param {function} callback The callback to call with the authorized client. 29 | */ 30 | function authorize(credentials, callback) { 31 | var clientSecret = credentials.installed.client_secret; 32 | var clientId = credentials.installed.client_id; 33 | var redirectUrl = credentials.installed.redirect_uris[0]; 34 | var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl); 35 | 36 | // Check if we have previously stored a token. 37 | fs.readFile(TOKEN_PATH, function(err, token) { 38 | if (err) { 39 | getNewToken(oauth2Client, callback); 40 | } else { 41 | oauth2Client.credentials = JSON.parse(token); 42 | callback(oauth2Client); 43 | } 44 | }); 45 | } 46 | 47 | /** 48 | * Get and store new token after prompting for user authorization, and then 49 | * execute the given callback with the authorized OAuth2 client. 50 | * 51 | * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for. 52 | * @param {getEventsCallback} callback The callback to call with the authorized 53 | * client. 54 | */ 55 | function getNewToken(oauth2Client, callback) { 56 | var authUrl = oauth2Client.generateAuthUrl({ 57 | access_type: 'offline', 58 | scope: SCOPES 59 | }); 60 | console.log('Authorize this app by visiting this url: ', authUrl); 61 | var rl = readline.createInterface({ 62 | input: process.stdin, 63 | output: process.stdout 64 | }); 65 | rl.question('Enter the code from that page here: ', function(code) { 66 | rl.close(); 67 | oauth2Client.getToken(code, function(err, token) { 68 | if (err) { 69 | console.log('Error while trying to retrieve access token', err); 70 | return; 71 | } 72 | oauth2Client.credentials = token; 73 | storeToken(token); 74 | callback(oauth2Client); 75 | }); 76 | }); 77 | } 78 | 79 | /** 80 | * Store token to disk be used in later program executions. 81 | * 82 | * @param {Object} token The token to store to disk. 83 | */ 84 | function storeToken(token) { 85 | try { 86 | fs.mkdirSync(TOKEN_DIR); 87 | } catch (err) { 88 | if (err.code != 'EEXIST') { 89 | throw err; 90 | } 91 | } 92 | fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { 93 | if (err) throw err; 94 | console.log('Token stored to ' + TOKEN_PATH); 95 | }); 96 | } 97 | 98 | /** 99 | * Lists the names and IDs of up to 10 files. 100 | * 101 | * @param {google.auth.OAuth2} auth An authorized OAuth2 client. 102 | */ 103 | function getChannel(auth) { 104 | var service = google.youtube('v3'); 105 | service.channels.list({ 106 | auth: auth, 107 | part: 'snippet,contentDetails,statistics', 108 | forUsername: 'GoogleDevelopers' 109 | }, function(err, response) { 110 | if (err) { 111 | console.log('The API returned an error: ' + err); 112 | return; 113 | } 114 | var channels = response.data.items; 115 | if (channels.length == 0) { 116 | console.log('No channel found.'); 117 | } else { 118 | console.log('This channel\'s ID is %s. Its title is \'%s\', and ' + 119 | 'it has %s views.', 120 | channels[0].id, 121 | channels[0].snippet.title, 122 | channels[0].statistics.viewCount); 123 | } 124 | }); 125 | } 126 | -------------------------------------------------------------------------------- /javascript/playlist_updates.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Playlist Updates 5 | 6 | 7 |
    This application requires access to your YouTube account. 8 | Please authorize to continue. 9 |
    10 |
    11 | 12 |
    13 | 14 |
    15 | 16 |
    17 |

    Playlist:

    18 |

    19 |
    20 | No Videos 21 |
    22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /javascript/playlist_updates.js: -------------------------------------------------------------------------------- 1 | // Define some variables used to remember state. 2 | var playlistId, channelId; 3 | 4 | // After the API loads, call a function to enable the playlist creation form. 5 | function handleAPILoaded() { 6 | enableForm(); 7 | } 8 | 9 | // Enable the form for creating a playlist. 10 | function enableForm() { 11 | $('#playlist-button').attr('disabled', false); 12 | } 13 | 14 | // Create a private playlist. 15 | function createPlaylist() { 16 | var request = gapi.client.youtube.playlists.insert({ 17 | part: 'snippet,status', 18 | resource: { 19 | snippet: { 20 | title: 'Test Playlist', 21 | description: 'A private playlist created with the YouTube API' 22 | }, 23 | status: { 24 | privacyStatus: 'private' 25 | } 26 | } 27 | }); 28 | request.execute(function(response) { 29 | var result = response.result; 30 | if (result) { 31 | playlistId = result.id; 32 | $('#playlist-id').val(playlistId); 33 | $('#playlist-title').html(result.snippet.title); 34 | $('#playlist-description').html(result.snippet.description); 35 | } else { 36 | $('#status').html('Could not create playlist'); 37 | } 38 | }); 39 | } 40 | 41 | // Add a video ID specified in the form to the playlist. 42 | function addVideoToPlaylist() { 43 | addToPlaylist($('#video-id').val()); 44 | } 45 | 46 | // Add a video to a playlist. The "startPos" and "endPos" values let you 47 | // start and stop the video at specific times when the video is played as 48 | // part of the playlist. However, these values are not set in this example. 49 | function addToPlaylist(id, startPos, endPos) { 50 | var details = { 51 | videoId: id, 52 | kind: 'youtube#video' 53 | } 54 | if (startPos != undefined) { 55 | details['startAt'] = startPos; 56 | } 57 | if (endPos != undefined) { 58 | details['endAt'] = endPos; 59 | } 60 | var request = gapi.client.youtube.playlistItems.insert({ 61 | part: 'snippet', 62 | resource: { 63 | snippet: { 64 | playlistId: playlistId, 65 | resourceId: details 66 | } 67 | } 68 | }); 69 | request.execute(function(response) { 70 | $('#status').html('
    ' + JSON.stringify(response.result) + '
    '); 71 | }); 72 | } 73 | -------------------------------------------------------------------------------- /javascript/quickstart.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | YouTube Data API Quickstart 5 | 6 | 7 | 8 |

    YouTube Data API Quickstart

    9 | 10 | 11 | 12 | 13 | 14 |
    
     15 | 
     16 |     
    114 | 
    115 |     
    119 |   
    120 | 
    121 | 
    
    
    --------------------------------------------------------------------------------
    /javascript/search.html:
    --------------------------------------------------------------------------------
     1 | 
     2 | 
     3 |   
     4 |     Search
     5 |   
     6 |   
     7 |     
    8 | 9 |
    10 |
    11 |
    12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /javascript/search.js: -------------------------------------------------------------------------------- 1 | // After the API loads, call a function to enable the search box. 2 | function handleAPILoaded() { 3 | $('#search-button').attr('disabled', false); 4 | } 5 | 6 | // Search for a specified string. 7 | function search() { 8 | var q = $('#query').val(); 9 | var request = gapi.client.youtube.search.list({ 10 | q: q, 11 | part: 'snippet' 12 | }); 13 | 14 | request.execute(function(response) { 15 | var str = JSON.stringify(response.result); 16 | $('#search-container').html('
    ' + str + '
    '); 17 | }); 18 | } 19 | -------------------------------------------------------------------------------- /javascript/upload_video.css: -------------------------------------------------------------------------------- 1 | #channel-image { 2 | width: 2em; 3 | height: 2em; 4 | vertical-align: middle; 5 | } 6 | 7 | #channel-name { 8 | margin-left: 0.2em; 9 | margin-right: 0.2em; 10 | } 11 | 12 | #disclaimer { 13 | font-size: 0.75em; 14 | color: #aeaeae; 15 | max-width: 350px; 16 | } 17 | 18 | body { 19 | font-family: "Open Sans", sans-serif; 20 | font-size: 1.5em; 21 | } 22 | 23 | .post-sign-in { 24 | display: none; 25 | } 26 | 27 | .during-upload { 28 | display: none; 29 | } 30 | 31 | .post-upload { 32 | display: none; 33 | } 34 | 35 | label { 36 | display: block; 37 | } 38 | 39 | input[type="text"], textarea, progress { 40 | font-size: 0.75em; 41 | width: 15em; 42 | margin-bottom: 1em; 43 | padding: 0.5em; 44 | font-family: "Open Sans", sans-serif; 45 | } 46 | 47 | textarea { 48 | height: 7em; 49 | } 50 | -------------------------------------------------------------------------------- /javascript/upload_video.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | YouTube API Uploads via CORS 6 | 7 | 8 | 9 | 10 | 21 | 22 |