Go
This code sample calls the API's
playlistItems.list
method to retrieve a list of
videos uploaded to the channel associated with the request. The code also calls the
channels.list
method with the
mine
parameter set to
true
to retrieve the playlist ID that identifies
the channel's uploaded videos.
This example uses the
Go client library
.
package main
import (
"fmt"
"log"
"google.golang.org/api/youtube/v3"
)
// Retrieve playlistItems in the specified playlist
func playlistItemsList(service *youtube.Service, part string, playlistId string, pageToken string) *youtube.PlaylistItemListResponse {
call := service.PlaylistItems.List(part)
call = call.PlaylistId(playlistId)
if pageToken != "" {
call = call.PageToken(pageToken)
}
response, err := call.Do()
handleError(err, "")
return response
}
// Retrieve resource for the authenticated user's channel
func channelsListMine(service *youtube.Service, part string) *youtube.ChannelListResponse {
call := service.Channels.List(part)
call = call.Mine(true)
response, err := call.Do()
handleError(err, "")
return response
}
func main() {
client := getClient(youtube.YoutubeReadonlyScope)
service, err := youtube.New(client)
if err != nil {
log.Fatalf("Error creating YouTube client: %v", err)
}
response := channelsListMine(service, "contentDetails")
for _, channel := range response.Items {
playlistId := channel.ContentDetails.RelatedPlaylists.Uploads
// Print the playlist ID for the list of uploaded videos.
fmt.Printf("Videos in list %s\r\n", playlistId)
nextPageToken := ""
for {
// Retrieve next set of items in the playlist.
playlistResponse := playlistItemsList(service, "snippet", playlistId, nextPageToken)
for _, playlistItem := range playlistResponse.Items {
title := playlistItem.Snippet.Title
videoId := playlistItem.Snippet.ResourceId.VideoId
fmt.Printf("%v, (%v)\r\n", title, videoId)
}
// Set the token to retrieve the next page of results
// or exit the loop if all results have been retrieved.
nextPageToken = playlistResponse.NextPageToken
if nextPageToken == "" {
break
}
fmt.Println()
}
}
}
.NET
The following code sample calls the API's
playlistItems.list
method to retrieve a list of videos
uploaded to the channel associated with the request. The code also calls the
channels.list
method with the
mine
parameter set to
true
to retrieve the playlist ID that identifies the channel's uploaded
videos.
This example uses the
.NET client library
.
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: retrieve my uploads.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://developers.google.com/api-client-library/dotnet/get_started
/// </summary>
internal class MyUploads
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: My Uploads");
Console.WriteLine("============================");
try
{
new MyUploads().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for read-only access to the authenticated
// user's account, but not other types of account access.
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Mine = true;
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
// From the API response, extract the playlist ID that identifies the list
// of videos uploaded to the authenticated user's channel.
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
Console.WriteLine("Videos in list {0}", uploadsListId);
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
// Print information about each video.
Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
}
}
Ruby
This sample calls the API's
playlistItems.list
method to retrieve a list of videos uploaded
to the channel associated with the request. The code also calls the
channels.list
method with the
mine
parameter set to
true
to retrieve the playlist ID that identifies the channel's
uploaded videos.
This example uses the
Ruby client library
.
#!/usr/bin/ruby
require 'rubygems'
gem 'google-api-client', '>0.7'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
# This OAuth 2.0 access scope allows for read-only access to the authenticated
# user's account, but not other types of account access.
YOUTUBE_READONLY_SCOPE = 'https://www.googleapis.com/auth/youtube.readonly'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def get_authenticated_service
client = Google::APIClient.new(
:application_name => $PROGRAM_NAME,
:application_version => '1.0.0'
)
youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
file_storage = Google::APIClient::FileStorage.new("#{$PROGRAM_NAME}-oauth2.json")
if file_storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => [YOUTUBE_READONLY_SCOPE]
)
client.authorization = flow.authorize(file_storage)
else
client.authorization = file_storage.authorization
end
return client, youtube
end
def main
client, youtube = get_authenticated_service
begin
# Retrieve the "contentDetails" part of the channel resource for the
# authenticated user's channel.
channels_response = client.execute!(
:api_method => youtube.channels.list,
:parameters => {
:mine => true,
:part => 'contentDetails'
}
)
channels_response.data.items.each do |channel|
# From the API response, extract the playlist ID that identifies the list
# of videos uploaded to the authenticated user's channel.
uploads_list_id = channel['contentDetails']['relatedPlaylists']['uploads']
# Retrieve the list of videos uploaded to the authenticated user's channel.
next_page_token = ''
until next_page_token.nil?
playlistitems_response = client.execute!(
:api_method => youtube.playlist_items.list,
:parameters => {
:playlistId => uploads_list_id,
:part => 'snippet',
:maxResults => 50,
:pageToken => next_page_token
}
)
puts "Videos in list #{uploads_list_id}"
# Print information about each video.
playlistitems_response.data.items.each do |playlist_item|
title = playlist_item['snippet']['title']
video_id = playlist_item['snippet']['resourceId']['videoId']
puts "#{title} (#{video_id})"
end
next_page_token = playlistitems_response.next_page_token
end
puts
end
rescue Google::APIClient::TransmissionError => e
puts e.result.body
end
end
main