이 페이지의 나머지 부분에 설명된 단계를 완료하면 약 5분 만에 YouTube Data API에 요청을 보내는 간단한 Node.js 명령줄 애플리케이션이 완성됩니다.
이 가이드에 사용된 샘플 코드는 GoogleDevelopers YouTube 채널의channel 리소스를 가져와 해당 리소스의 기본 정보를 출력합니다.
기본 요건
이 빠른 시작을 실행하려면 다음이 필요합니다.
- Node.js가 설치되어 있습니다.
- npm 패키지 관리 도구 (Node.js와 함께 제공됨)
- 인터넷 및 웹브라우저 액세스
- Google 계정
1단계: YouTube Data API 사용 설정
- 
  이 마법사를 사용하여 Google Developers Console에서 프로젝트를 만들거나 선택하고 API를 자동으로 사용 설정합니다. 계속을 클릭한 다음 사용자 인증 정보로 이동을 클릭합니다. 
- 
  사용자 인증 정보 만들기 페이지에서 취소 버튼을 클릭합니다. 
- 
  페이지 상단에서 OAuth 동의 화면 탭을 선택합니다. 이메일 주소를 선택하고, 아직 설정되지 않은 경우 제품 이름을 입력한 다음 저장 버튼을 클릭합니다. 
- 
  사용자 인증 정보 탭을 선택하고 사용자 인증 정보 만들기 버튼을 클릭한 후 OAuth 클라이언트 ID를 선택합니다. 
- 
  애플리케이션 유형 기타를 선택하고 이름에 'YouTube Data API Quickstart'를 입력한 후 만들기 버튼을 클릭합니다. 
- 
  확인을 클릭하여 결과 대화상자를 닫습니다. 
- 
  클라이언트 ID 오른쪽에 있는 (JSON 다운로드) 버튼을 클릭합니다. 
- 
  다운로드한 파일을 작업 디렉터리로 이동하고 이름을 client_secret.json로 변경합니다.
2단계: 클라이언트 라이브러리 설치
다음 명령어를 실행하여 npm을 사용하여 라이브러리를 설치합니다.
npm install googleapis --savenpm 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
샘플을 처음 실행하면 액세스 권한을 부여하라는 메시지가 표시됩니다.
- 웹브라우저에서 제공된 URL로 이동합니다. - 아직 Google 계정에 로그인하지 않은 경우 로그인하라는 메시지가 표시됩니다. 여러 Google 계정에 로그인한 경우 인증에 사용할 계정을 선택하라는 메시지가 표시됩니다. 
- 수락 버튼을 클릭합니다.
- 제공된 코드를 복사하여 명령줄 프롬프트에 붙여넣고 Enter 키를 누릅니다.
참고
- 승인 정보는 파일 시스템에 저장되므로 후속 실행에서는 승인을 묻는 메시지가 표시되지 않습니다.
- 이 예의 승인 흐름은 명령줄 애플리케이션용으로 설계되었습니다. YouTube Data API를 사용하는 웹 애플리케이션에서 승인을 실행하는 방법에 관한 자세한 내용은 웹 서버 애플리케이션용 OAuth 2.0 사용을 참고하세요.
 다른 컨텍스트에서 승인을 실행하는 방법에 관한 자세한 내용은 라이브러리 README의 승인 및 인증 섹션을 참고하세요.