Node.js 빠른 시작

이 페이지의 나머지 부분에 설명된 단계를 완료하면 약 5분 후에 YouTube Data API에 요청하는 간단한 Node.js 명령줄 애플리케이션을 사용할 수 있습니다.

이 가이드에 사용된 샘플 코드는 GoogleDevelopers YouTube 채널의 channel 리소스를 검색하고 이 리소스에서 기본 정보를 출력합니다.

기본 요건

이 빠른 시작을 실행하려면 다음이 필요합니다.

  • Node.js가 설치되었습니다.
  • npm 패키지 관리 도구 (Node.js와 함께 제공됨)
  • 인터넷 및 웹브라우저 액세스
  • Google 계정

1단계: YouTube Data API 사용 설정하기

  1. 이 마법사를 사용하여 Google Developers Console에서 프로젝트를 만들거나 선택하고 API를 자동으로 사용 설정하세요. 계속을 클릭한 다음 사용자 인증 정보로 이동을 클릭합니다.

  2. 사용자 인증 정보 만들기 페이지에서 취소 버튼을 클릭합니다.

  3. 페이지 상단에서 OAuth 동의 화면 탭을 선택합니다. 이메일 주소를 선택하고 아직 설정되지 않은 경우 제품 이름을 입력한 후 저장 버튼을 클릭합니다.

  4. 사용자 인증 정보 탭을 선택하고 사용자 인증 정보 만들기 버튼을 클릭한 후 OAuth 클라이언트 ID를 선택합니다.

  5. 애플리케이션 유형을 Other로 선택하고 'YouTube Data API quickstart'를 입력한 후 만들기 버튼을 클릭합니다.

  6. 확인을 클릭하여 표시되는 대화상자를 닫습니다.

  7. 클라이언트 ID 오른쪽에 있는 (JSON 다운로드) 버튼을 클릭합니다.

  8. 다운로드한 파일을 작업 디렉터리로 이동하고 이름을 client_secret.json로 변경합니다.

2단계: 클라이언트 라이브러리 설치하기

다음 명령어를 실행하여 npm을 사용하여 라이브러리를 설치합니다.

npm install googleapis --save
npm install google-auth-library --save

3단계: 샘플 설정

작업 디렉터리에 quickstart.js이라는 파일을 만들고 다음 코드를 복사합니다.

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}

4단계: 샘플 실행

다음 명령어를 사용하여 샘플을 실행합니다.

node quickstart.js

샘플을 처음 실행하면 액세스를 승인하라는 메시지가 표시됩니다.

  1. 웹브라우저에서 제공된 URL로 이동합니다.

    아직 Google 계정에 로그인하지 않은 경우 로그인하라는 메시지가 표시됩니다. 여러 Google 계정에 로그인되어 있는 경우 승인에 사용할 계정 한 개를 선택하라는 메시지가 표시됩니다.

  2. 수락 버튼을 클릭합니다.
  3. 제공된 코드를 복사하여 명령줄 프롬프트에 붙여넣고 Enter 키를 누릅니다.

메모

  • 승인 정보는 파일 시스템에 저장되므로 이후의 실행 시 승인 메시지가 표시되지 않습니다.
  • 이 예시의 승인 흐름은 명령줄 애플리케이션용으로 고안되었습니다. YouTube Data API를 사용하는 웹 애플리케이션에서 승인을 수행하는 방법에 대한 자세한 내용은 웹 서버 애플리케이션용 OAuth 2.0 사용을 참조하세요.

    다른 컨텍스트에서 승인을 실행하는 방법에 대한 자세한 내용은 라이브러리 README의 승인 및 인증 섹션을 참조하세요.

추가 자료