Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Hoàn tất các bước được mô tả trong phần còn lại của trang này và trong khoảng 5 phút, bạn sẽ có một ứng dụng dòng lệnh Node.js đơn giản để đưa ra yêu cầu cho YouTube Data API.
Mã mẫu được dùng trong hướng dẫn này sẽ truy xuất tài nguyên channel cho kênh GoogleDevelopers trên YouTube và in một số thông tin cơ bản từ tài nguyên đó.
Có quyền truy cập vào Internet và trình duyệt web.
Tài khoản Google.
Bước 1: Bật YouTube Data API
Sử dụng trình hướng dẫn này để tạo hoặc chọn một dự án trong Google Developers Console và tự động bật API. Nhấp vào Tiếp tục, rồi nhấp vào Chuyển đến phần thông tin đăng nhập.
Trên trang Tạo thông tin xác thực, hãy nhấp vào nút Huỷ.
Ở đầu trang, hãy chọn thẻ Màn hình xin phép bằng OAuth.
Chọn một Địa chỉ email, nhập Tên sản phẩm nếu chưa đặt và nhấp vào nút Lưu.
Chọn thẻ Thông tin xác thực, nhấp vào nút Tạo thông tin xác thực rồi chọn Mã ứng dụng OAuth.
Chọn loại ứng dụng Khác, nhập tên "YouTube Data API Quickstart" rồi nhấp vào nút Tạo.
Nhấp vào OK để đóng hộp thoại kết quả.
Nhấp vào nút file_download (Tải JSON xuống) ở bên phải mã nhận dạng ứng dụng.
Di chuyển tệp đã tải xuống vào thư mục đang hoạt động rồi đổi tên thành client_secret.json.
Tạo một tệp có tên là quickstart.js trong thư mục làm việc của bạn rồi sao chép mã sau vào:
varfs=require('fs');varreadline=require('readline');var{google}=require('googleapis');varOAuth2=google.auth.OAuth2;// If modifying these scopes, delete your previously saved credentials// at ~/.credentials/youtube-nodejs-quickstart.jsonvarSCOPES=['https://www.googleapis.com/auth/youtube.readonly'];varTOKEN_DIR=(process.env.HOME||process.env.HOMEPATH||process.env.USERPROFILE)+'/.credentials/';varTOKEN_PATH=TOKEN_DIR+'youtube-nodejs-quickstart.json';// Load client secrets from a local file.fs.readFile('client_secret.json',functionprocessClientSecrets(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. */functionauthorize(credentials,callback){varclientSecret=credentials.installed.client_secret;varclientId=credentials.installed.client_id;varredirectUrl=credentials.installed.redirect_uris[0];varoauth2Client=newOAuth2(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. */functiongetNewToken(oauth2Client,callback){varauthUrl=oauth2Client.generateAuthUrl({access_type:'offline',scope:SCOPES});console.log('Authorize this app by visiting this url: ',authUrl);varrl=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. */functionstoreToken(token){try{fs.mkdirSync(TOKEN_DIR);}catch(err){if(err.code!='EEXIST'){throwerr;}}fs.writeFile(TOKEN_PATH,JSON.stringify(token),(err)=>{if(err)throwerr;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. */functiongetChannel(auth){varservice=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;}varchannels=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);}});}
Trong lần đầu tiên bạn chạy mẫu, mẫu này sẽ nhắc bạn uỷ quyền truy cập:
Duyệt đến URL được cung cấp trong trình duyệt web.
Nếu chưa đăng nhập vào Tài khoản Google, bạn sẽ được nhắc đăng nhập. Nếu đã đăng nhập vào nhiều Tài khoản Google, bạn sẽ được yêu cầu chọn một tài khoản để dùng cho việc uỷ quyền.
Nhấp vào nút Chấp nhận.
Sao chép mã bạn nhận được, dán mã đó vào dấu nhắc dòng lệnh rồi nhấn phím Enter.
Ghi chú
Thông tin uỷ quyền được lưu trữ trên hệ thống tệp, vì vậy, các lần thực thi tiếp theo sẽ không nhắc bạn uỷ quyền.
Quy trình uỷ quyền trong ví dụ này được thiết kế cho một ứng dụng dòng lệnh. Để biết thông tin về cách thực hiện việc uỷ quyền trong một ứng dụng web sử dụng YouTube Data API, hãy xem bài viết Sử dụng OAuth 2.0 cho ứng dụng máy chủ web.
Để biết thông tin về cách thực hiện việc uỷ quyền trong các bối cảnh khác, hãy xem phần Uỷ quyền và xác thực trong tệp README của thư viện.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-21 UTC."],[[["\u003cp\u003eThis guide walks you through creating a simple Node.js command-line application that interacts with the YouTube Data API to retrieve and display information from a YouTube channel in about five minutes.\u003c/p\u003e\n"],["\u003cp\u003eYou will need Node.js, npm, internet access, a web browser, and a Google account to complete the steps in this guide.\u003c/p\u003e\n"],["\u003cp\u003eThe setup involves enabling the YouTube Data API in the Google Developers Console, installing the necessary client libraries, setting up a \u003ccode\u003equickstart.js\u003c/code\u003e file with the provided code, and obtaining OAuth 2.0 credentials.\u003c/p\u003e\n"],["\u003cp\u003eRunning \u003ccode\u003enode quickstart.js\u003c/code\u003e will execute the sample code to retrieve and display basic information about the GoogleDevelopers YouTube channel.\u003c/p\u003e\n"],["\u003cp\u003eThe application stores authorization information on the file system, avoiding repeated authorization prompts on subsequent runs.\u003c/p\u003e\n"]]],["This guide outlines how to set up a Node.js command-line application to interact with the YouTube Data API. Key actions include: enabling the API via the Google Developers Console, creating OAuth credentials, and downloading the `client_secret.json` file. You will also need to install the `googleapis` and `google-auth-library` npm packages. Then, create a `quickstart.js` file with sample code, and run it. The first run requires browser authorization and code input, while subsequent runs will use stored authorization data. The code retrieves and displays channel data from the YouTube Data API.\n"],null,["# Node.js Quickstart\n\nComplete the steps described in the rest of this page, and in about five minutes\nyou'll have a simple Node.js command-line application that makes requests to the\nYouTube Data API.\nThe sample code used in this guide retrieves the `channel` resource for the GoogleDevelopers YouTube channel and prints some basic information from that resource.\n\nPrerequisites\n-------------\n\nTo run this quickstart, you'll need:\n\n- Node.js installed.\n- The [npm](https://www.npmjs.com/) package management tool (comes with Node.js).\n- Access to the internet and a web browser.\n- A Google account.\n\nStep 1: Turn on the YouTube Data API\n------------------------------------\n\n1. Use\n [this wizard](https://console.developers.google.com/start/api?id=youtube)\n to create or select a project in the Google Developers Console and\n automatically turn on the API. Click **Continue** , then\n **Go to credentials**.\n\n2. On the **Create credentials** page, click the\n **Cancel** button.\n\n3. At the top of the page, select the **OAuth consent screen** tab.\n Select an **Email address** , enter a **Product name** if not\n already set, and click the **Save** button.\n\n4. Select the **Credentials** tab, click the **Create credentials**\n button and select **OAuth client ID**.\n\n5. Select the application type **Other** , enter the name\n \"YouTube Data API Quickstart\", and click the **Create** button.\n\n6. Click **OK** to dismiss the resulting dialog.\n\n7. Click the file_download\n (Download JSON) button to the right of the client ID.\n\n8. Move the downloaded file to your working directory and rename it\n `client_secret.json`.\n\nStep 2: Install the client library\n----------------------------------\n\nRun the following commands to install the libraries using npm: \n\n npm install googleapis --save\n npm install google-auth-library --save\n\nStep 3: Set up the sample\n-------------------------\n\nCreate a file named `quickstart.js` in your working directory and copy in\nthe following code:\n\n\n```javascript\nvar fs = require('fs');\nvar readline = require('readline');\nvar {google} = require('googleapis');\nvar OAuth2 = google.auth.OAuth2;\n\n// If modifying these scopes, delete your previously saved credentials\n// at ~/.credentials/youtube-nodejs-quickstart.json\nvar SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];\nvar TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||\n process.env.USERPROFILE) + '/.credentials/';\nvar TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';\n\n// Load client secrets from a local file.\nfs.readFile('client_secret.json', function processClientSecrets(err, content) {\n if (err) {\n console.log('Error loading client secret file: ' + err);\n return;\n }\n // Authorize a client with the loaded credentials, then call the YouTube API.\n authorize(JSON.parse(content), getChannel);\n});\n\n/**\n * Create an OAuth2 client with the given credentials, and then execute the\n * given callback function.\n *\n * @param {Object} credentials The authorization client credentials.\n * @param {function} callback The callback to call with the authorized client.\n */\nfunction authorize(credentials, callback) {\n var clientSecret = credentials.installed.client_secret;\n var clientId = credentials.installed.client_id;\n var redirectUrl = credentials.installed.redirect_uris[0];\n var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);\n\n // Check if we have previously stored a token.\n fs.readFile(TOKEN_PATH, function(err, token) {\n if (err) {\n getNewToken(oauth2Client, callback);\n } else {\n oauth2Client.credentials = JSON.parse(token);\n callback(oauth2Client);\n }\n });\n}\n\n/**\n * Get and store new token after prompting for user authorization, and then\n * execute the given callback with the authorized OAuth2 client.\n *\n * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.\n * @param {getEventsCallback} callback The callback to call with the authorized\n * client.\n */\nfunction getNewToken(oauth2Client, callback) {\n var authUrl = oauth2Client.generateAuthUrl({\n access_type: 'offline',\n scope: SCOPES\n });\n console.log('Authorize this app by visiting this url: ', authUrl);\n var rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n rl.question('Enter the code from that page here: ', function(code) {\n rl.close();\n oauth2Client.getToken(code, function(err, token) {\n if (err) {\n console.log('Error while trying to retrieve access token', err);\n return;\n }\n oauth2Client.credentials = token;\n storeToken(token);\n callback(oauth2Client);\n });\n });\n}\n\n/**\n * Store token to disk be used in later program executions.\n *\n * @param {Object} token The token to store to disk.\n */\nfunction storeToken(token) {\n try {\n fs.mkdirSync(TOKEN_DIR);\n } catch (err) {\n if (err.code != 'EEXIST') {\n throw err;\n }\n }\n fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) =\u003e {\n if (err) throw err;\n console.log('Token stored to ' + TOKEN_PATH);\n });\n}\n\n/**\n * Lists the names and IDs of up to 10 files.\n *\n * @param {google.auth.OAuth2} auth An authorized OAuth2 client.\n */\nfunction getChannel(auth) {\n var service = google.youtube('v3');\n service.channels.list({\n auth: auth,\n part: 'snippet,contentDetails,statistics',\n forUsername: 'GoogleDevelopers'\n }, function(err, response) {\n if (err) {\n console.log('The API returned an error: ' + err);\n return;\n }\n var channels = response.data.items;\n if (channels.length == 0) {\n console.log('No channel found.');\n } else {\n console.log('This channel\\'s ID is %s. Its title is \\'%s\\', and ' +\n 'it has %s views.',\n channels[0].id,\n channels[0].snippet.title,\n channels[0].statistics.viewCount);\n }\n });\n}\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/javascript/nodejs-quickstart.js\n```\n\n\u003cbr /\u003e\n\nStep 4: Run the sample\n----------------------\n\nRun the sample using the following command: \n\n node quickstart.js\n\nThe first time you run the sample, it will prompt you to authorize access:\n\n1. Browse to the provided URL in your web browser.\n\n If you are not already logged into your Google account, you will be\n prompted to log in. If you are logged into multiple Google accounts, you\n will be asked to select one account to use for the authorization.\n2. Click the **Accept** button.\n3. Copy the code you're given, paste it into the command-line prompt, and press **Enter**.\n\nIt worked! **Great!** Check out the further reading section below to learn more.\nI got an error **Bummer.** Thanks for letting us know and we'll work to fix this quickstart.\n\nNotes\n-----\n\n- Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.\n- The authorization flow in this example is designed for a command line application. For information on how to perform authorization in a web application that uses the YouTube Data API, see [Using OAuth 2.0 for Web Server Applications](/youtube/v3/guides/auth/server-side-web-apps). \n\n For information on how to perform authorization in other contexts, see the [Authorizing and Authenticating](https://github.com/google/google-api-nodejs-client/#authorizing-and-authenticating) section of the library's README.\n\nFurther reading\n---------------\n\n- [Google Developers Console help documentation](/console/help/new)\n- [Google APIs Client for Node.js documentation](https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client)\n- [YouTube Data API reference documentation](/youtube/v3/docs)"]]