完成本頁其餘部分所述的步驟,大約五分鐘後,您就會擁有一個簡單的 Node.js 指令列應用程式,可向 YouTube Data API 提出要求。
本指南使用的範例程式碼會擷取 GoogleDevelopers YouTube 頻道的channel
資源,並從該資源列印一些基本資訊。
必要條件
如要執行這項快速入門導覽課程,您需要:
- 已安裝 Node.js。
- npm 套件管理工具 (隨附於 Node.js)。
- 網路連線和網路瀏覽器。
- Google 帳戶。
步驟 1:開啟 YouTube Data API
-
使用這個精靈在 Google Developers Console 中建立或選取專案,並自動啟用 API。依序點按「繼續」和「前往憑證」。
-
在「建立憑證」頁面中,按一下「取消」按鈕。
-
選取頁面頂端的「OAuth 同意畫面」分頁標籤。 選取「電子郵件地址」,輸入「產品名稱」 (如果尚未設定),然後按一下「儲存」按鈕。
-
選取「憑證」分頁,按一下「建立憑證」按鈕,然後選取「OAuth 用戶端 ID」。
-
選取「Other」(其他) 應用程式類型,輸入名稱「YouTube Data API Quickstart」,然後按一下「Create」(建立) 按鈕。
-
按一下「確定」關閉隨即顯示的對話方塊。
-
按一下用戶端 ID 右側的「下載 JSON」
按鈕。 -
將下載的檔案移到工作目錄,並重新命名為
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
第一次執行範例時,系統會提示您授權存取權:
在網路瀏覽器中瀏覽至提供的網址。
如果尚未登入 Google 帳戶,系統會提示你登入。如果您登入了多個 Google 帳戶,系統會要求您選取一個帳戶進行授權。
- 按一下「接受」按鈕。
- 複製系統提供的程式碼,貼到指令列提示中,然後按下 Enter 鍵。
附註
- 授權資訊會儲存在檔案系統中,因此後續執行作業時不會提示授權。
- 本範例中的授權流程是為指令列應用程式設計。如要瞭解如何在採用 YouTube Data API 的網路應用程式中執行授權,請參閱「針對網路伺服器應用程式使用 OAuth 2.0」。
如要瞭解如何在其他情境中執行授權,請參閱程式庫 README 的「Authorizing and Authenticating」(授權和驗證) 一節。