YouTube Data API (v3) 는 정말 많은 내용을 제공해주고 있는데 물론 API 할당량은 제한적이다.
그래도 무료 버전으로 혼자서 갖고 놀기에는 충분하다. ( 돈을 더 지불하면 얼마든지... )
우선 API 요청에 대한 인증 파일을 생성하는데 이것도 코드 샘플을 제공해준다.
https://developers.google.com/youtube/v3/code_samples/javascript?hl=ko#authorizing_requests
auth.js
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
console.log(authResult);
if (authResult && !authResult.error) {
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
});
}
Java Script 같은 static 파일의 경로는 {프로젝트명}/static/js 디렉토리로 설정해준다.
구글에서 제공해주는 코드 샘플과 조금은 다른 형태인데 OAUTH2_CLIENT_ID 를 다른 스크립트 파일로 따로 분리해서 나중에 코드 커밋 시 과금 폭탄을 미연에 방지할 수 있다...
env.js
const OAUTH2_CLIENT_ID = "123456789.apps.googleusercontent.com";
해당 client ID 값은 google api console 사용자 인증 정보에 'OAuth 2.0 클라이언트 ID' 부분을 참고하면 된다.
이제 API에서 제공하는 channels 리소스를 사용하여 좋아요한 동영상 목록을 만들어 본다.
https://developers.google.com/youtube/v3/docs/channels?hl=ko
channels.js
// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken;
// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
requestUserUploadsPlaylistId();
}
// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
// See https://developers.google.com/youtube/v3/docs/channels/list
var request = gapi.client.youtube.channels.list({
mine: true,
part: 'contentDetails'
});
request.execute(function(response) {
playlistId = response.result.items[0].contentDetails.relatedPlaylists.likes;
// See https://developers.google.com/youtube/v3/docs/channels?hl=ko
requestVideoPlaylist(playlistId);
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
$('#video-container').html('');
var requestOptions = {
playlistId: playlistId,
part: 'snippet',
maxResults: 10
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('#next-button').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('#prev-button').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function(index, item) {
displayResult(item.snippet);
});
} else {
$('#video-container').html('Sorry you have no uploaded videos');
}
});
}
// Create a listing for a video.
function displayResult(videoSnippet) {
var title = videoSnippet.title;
var videoId = videoSnippet.resourceId.videoId;
// $('#video-container').append('<p>' + title + ' - ' + videoId + '</p>');
$('#video-container').append("<iframe width='640' height='320' src='https://www.youtube.com/embed/"+videoId+"'>");
}
// Retrieve the next page of videos in the playlist.
function nextPage() {
requestVideoPlaylist(playlistId, nextPageToken);
}
// Retrieve the previous page of videos in the playlist.
function previousPage() {
requestVideoPlaylist(playlistId, prevPageToken);
}
갓글에서 제공해준 '내가 업로드한 동영상' 샘플 코드를 iframe html 태그를 사용하도록 수정하였다.
https://developers.google.com/youtube/v3/code_samples/javascript?hl=ko#my_uploaded_videos
response.result.items[0].contentDetails.relatedPlaylists 로그를 찍어보면 아래와 같은 값을 리턴하는데 여기서 나는 likes 를 사용했다.
{- likes:"LLaqYkTQH7KUznvIm91EMJ0g",
- favorites:"FLaqYkTQH7KUznvIm91EMJ0g",
- uploads:"UUaqYkTQH7KUznvIm91EMJ0g",
- watchHistory:"HL",
- watchLater:"WL"
}
자 그럼 이제 장고 탬플릿에 js 파일을 로드 한 다음 로컬 서버를 띄워 보자
구글 계정 로그인을 완료하면 계정의 좋아요를 누른 모든 동영상들이 나타나게 된다. 나는 1,900개 이상이더라 😟

나 같은 자알못도 이런 샘플 코드로 자바 스크립트 맛을 보게 해주는 갓글에게 다시 한번 박수를.....
완성 코드 : https://github.com/XXOK/Youtube_API