JavaScript 코드 예

JavaScript용 Google API 클라이언트 라이브러리를 사용하는 다음 코드 샘플은 YouTube Data API에 사용할 수 있습니다. 이 코드 샘플들은 GitHub의 YouTube API 코드 샘플 리포지토리javascript 폴더에서 받으실 수 있습니다.

요청 인증

  • JavaScript (auth.js)

    auth.js 스크립트는 API 액세스를 제공하고 사용자 요청을 인증하기 위해 JavaScript용 Google API 클라이언트 라이브러리를 사용하는 방법을 보여줍니다. 이 페이지에서 이후에 나오는 모든 샘플은 이 스크립트를 사용하여 요청을 인증합니다.

    인증이 필요하지 않은 요청에는 OAuth 2.0을 사용하지 않고 key 쿼리 매개변수를 사용하여 API 키를 지정할 수도 있습니다.

    참고: auth.js 파일의 클라이언트 ID를 업데이트해야 합니다. Google API Console에서 애플리케이션을 등록하여 고유한 클라이언트 ID를 얻을 수 있습니다.

    // The client ID is obtained from the Google API Console
    // at https://console.cloud.google.com/.
    // If you run this code from a server other than http://localhost,
    // you need to register your own client ID.
    var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
    var OAUTH2_SCOPES = [
      'https://www.googleapis.com/auth/youtube'
    ];
    
    // Upon loading, the Google APIs JS client automatically invokes this callback.
    googleApiClientReady = function() {
      gapi.auth.init(function() {
        window.setTimeout(checkAuth, 1);
      });
    }
    
    // Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
    // If the currently logged-in Google Account has previously authorized
    // the client specified as the OAUTH2_CLIENT_ID, then the authorization
    // succeeds with no user intervention. Otherwise, it fails and the
    // user interface that prompts for authorization needs to display.
    function checkAuth() {
      gapi.auth.authorize({
        client_id: OAUTH2_CLIENT_ID,
        scope: OAUTH2_SCOPES,
        immediate: true
      }, handleAuthResult);
    }
    
    // Handle the result of a gapi.auth.authorize() call.
    function handleAuthResult(authResult) {
      if (authResult && !authResult.error) {
        // Authorization was successful. Hide authorization prompts and show
        // content that should be visible after authorization succeeds.
        $('.pre-auth').hide();
        $('.post-auth').show();
        loadAPIClientInterfaces();
      } else {
        // Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
        // client flow. The current function is called when that flow completes.
        $('#login-link').click(function() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: false
            }, handleAuthResult);
        });
      }
    }
    
    // Load the client interfaces for the YouTube Analytics and Data APIs, which
    // are required to use the Google APIs JS client. More info is available at
    // https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api
    function loadAPIClientInterfaces() {
      gapi.client.load('youtube', 'v3', function() {
        handleAPILoaded();
      });
    }

내가 올린 동영상

아래의 코드 샘플은 인증된 사용자의 채널에 업로드된 동영상을 나열하는 애플리케이션용입니다. 이 코드는 JavaScript와 CSS 파일이 HTML 페이지와 같은 디렉토리에 있다고 가정합니다.

  • JavaScript (my_uploads.js)

    아래의 JavaScript 코드는 다음과 같은 기능을 수행합니다.

    1. API의 channels.list 메소드를 사용하여 사용자의 채널에 업로드된 동영상의 재생목록 ID를 검색합니다.
    2. 이 ID를 playlistItems.list 메소드에 전달하여 목록에서 동영상을 검색합니다.
    3. 동영상 목록을 표시합니다.
    4. API 응답의 정보를 기준으로 다음 및 이전 페이지 버튼을 구성하고 공개 상태를 설정합니다.

    요청 인증 섹션에 설명된 대로 이 코드를 실행하려면 auth.js 파일의 클라이언트 ID를 업데이트해야 합니다.

    // 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.uploads;
        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>');
    }
    
    // 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);
    }
  • HTML (my_uploads.html)

    아래의 HTML 페이지는 위에 표시된 JQuery, auth.js, my_uploads.js JavaScript 파일과 CSS 파일을 사용하여 업로드된 동영상의 목록을 표시합니다.

    <!doctype html>
    <html>
      <head>
        <title>My Uploads</title>
        <link rel="stylesheet" type="text/css" href="my_uploads.css">
      </head>
      <body>
        <div id="login-container" class="pre-auth">
          This application requires access to your YouTube account.
          Please <a href="#" id="login-link">authorize</a> to continue.
        </div>
        <div id="video-container"></div>
        <div class="button-container">
          <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
          <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
        </div>
        <script src="https://www.gstatic.com/external_hosted/jquery2.min.js"></script>
        <script type="text/javascript" src="auth.js"></script>
        <script type="text/javascript" src="my_uploads.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>
  • CSS (my_uploads.css)

    또한 이 샘플 앱은 다음 CSS를 사용합니다.

    .paging-button {
      visibility: hidden;
    }
    
    .button-container {
      clear: both;
    }

재생목록 만들기

아래의 코드 샘플은 사용자가 비공개 재생목록을 만들고 그 목록에 동영상을 추가하기 위해 사용하는 애플리케이션용입니다. (코드를 수정하여 모두에게 공개되는 재생목록을 만들거나 재생목록의 공개/비공개 여부를 결정할 수 있는 양식 값을 선택할 수도 있습니다.)

  • JavaScript (playlist_updates.js)

    아래의 JavaScript 코드는 다음과 같은 기능을 수행합니다.

    1. 비공개 재생목록을 만들고 새로 만든 재생목록에 대한 정보를 표시할 수 있습니다.
    2. 재생목록에 동영상을 추가하고 이 작업에 대한 API 응답을 표시합니다. JavaScript 코드는 동영상이 재생을 시작하고 중지하는 위치를 지정하는 기능을 지원하지만 아래의 HTML은 이러한 값을 지정하는 방법을 제공하지 않습니다.

    또한 이 코드를 실행하려면 auth.js 파일의 클라이언트 ID를 업데이트해야 합니다.

    // Define some variables used to remember state.
    var playlistId, channelId;
    
    // After the API loads, call a function to enable the playlist creation form.
    function handleAPILoaded() {
      enableForm();
    }
    
    // Enable the form for creating a playlist.
    function enableForm() {
      $('#playlist-button').attr('disabled', false);
    }
    
    // Create a private playlist.
    function createPlaylist() {
      var request = gapi.client.youtube.playlists.insert({
        part: 'snippet,status',
        resource: {
          snippet: {
            title: 'Test Playlist',
            description: 'A private playlist created with the YouTube API'
          },
          status: {
            privacyStatus: 'private'
          }
        }
      });
      request.execute(function(response) {
        var result = response.result;
        if (result) {
          playlistId = result.id;
          $('#playlist-id').val(playlistId);
          $('#playlist-title').html(result.snippet.title);
          $('#playlist-description').html(result.snippet.description);
        } else {
          $('#status').html('Could not create playlist');
        }
      });
    }
    
    // Add a video ID specified in the form to the playlist.
    function addVideoToPlaylist() {
      addToPlaylist($('#video-id').val());
    }
    
    // Add a video to a playlist. The "startPos" and "endPos" values let you
    // start and stop the video at specific times when the video is played as
    // part of the playlist. However, these values are not set in this example.
    function addToPlaylist(id, startPos, endPos) {
      var details = {
        videoId: id,
        kind: 'youtube#video'
      }
      if (startPos != undefined) {
        details['startAt'] = startPos;
      }
      if (endPos != undefined) {
        details['endAt'] = endPos;
      }
      var request = gapi.client.youtube.playlistItems.insert({
        part: 'snippet',
        resource: {
          snippet: {
            playlistId: playlistId,
            resourceId: details
          }
        }
      });
      request.execute(function(response) {
        $('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
      });
    }
  • HTML (playlist_updates.html)

    아래의 HTML 페이지는 위에 표시된 auth.jsplaylist_updates.js JavaScript 파일과 함께 JQuery를 사용합니다.

    <!doctype html>
    <html>
      <head>
        <title>Playlist Updates</title>
      </head>
      <body>
        <div id="login-container" class="pre-auth">This application requires access to your YouTube account.
          Please <a href="#" id="login-link">authorize</a> to continue.
        </div>
        <div id="buttons">
          <button id="playlist-button" disabled onclick="createPlaylist()">Create a new Private Playlist</button>
          <br>
          <label>Current Playlist Id: <input id="playlist-id" value='' type="text"/></label>
          <br>
          <label>Video Id: <input id="video-id" value='GZG9G5txtaE' type="text"/></label><button onclick="addVideoToPlaylist()">Add to current playlist</button>
        </div>
        <h3>Playlist: <span id="playlist-title"></span></h3>
        <p id="playlist-description"></p>
        <div id="playlist-container">
          <span id="status">No Videos</span>
        </div>
        <script src="https://www.gstatic.com/external_hosted/jquery2.min.js"></script>
        <script src="auth.js"></script>
        <script src="playlist_updates.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>

키워드별 검색

아래의 코드 샘플은 지정된 쿼리에 대해 YouTube 검색을 실행하고 API 결과를 표시하는 애플리케이션용입니다.

  • JavaScript (search.js)

    아래의 JavaScript 코드는 지정된 검색어로 YouTube 검색을 실행하고 API 응답으로 DOM 요소를 채웁니다. 또한 이 코드를 실행하려면 auth.js 파일의 클라이언트 ID를 업데이트해야 합니다.

    // After the API loads, call a function to enable the search box.
    function handleAPILoaded() {
      $('#search-button').attr('disabled', false);
    }
    
    // Search for a specified string.
    function search() {
      var q = $('#query').val();
      var request = gapi.client.youtube.search.list({
        q: q,
        part: 'snippet'
      });
    
      request.execute(function(response) {
        var str = JSON.stringify(response.result);
        $('#search-container').html('<pre>' + str + '</pre>');
      });
    }
  • HTML (search.html)

    아래의 HTML 페이지는 위에 표시된 auth.jssearch.js JavaScript 파일과 함께 JQuery를 사용하여 검색 결과의 목록을 표시합니다.

    <!doctype html>
    <html>
      <head>
        <title>Search</title>
      </head>
      <body>
        <div id="buttons">
          <label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
        </div>
        <div id="search-container">
        </div>
        <script src="https://www.gstatic.com/external_hosted/jquery2.min.js"></script>
        <script src="auth.js"></script>
        <script src="search.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>