Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Completa i passaggi descritti nel resto di questa pagina e in circa cinque minuti
avrai una semplice applicazione a riga di comando Node.js che effettua richieste all'API di dati di YouTube.
Il codice di esempio utilizzato in questa guida recupera la risorsa channel
per il canale YouTube GoogleDevelopers e stampa alcune informazioni di base
da questa risorsa.
Prerequisiti
Per eseguire questa guida rapida, devi disporre di:
Node.js installato.
Lo strumento di gestione pacchetti npm (fornito con
Node.js).
Accesso a internet e a un browser web.
Un Account Google.
Passaggio 1: attiva l'API YouTube Data
Utilizza
questa procedura guidata
per creare o selezionare un progetto nella Google Developers Console e
attivare automaticamente l'API. Fai clic su Continua, quindi su
Vai alle credenziali.
Nella pagina Crea credenziali, fai clic sul pulsante
Annulla.
Nella parte superiore della pagina, seleziona la scheda Schermata di consenso OAuth.
Seleziona un indirizzo email, inserisci un nome prodotto se non
è già impostato e fai clic sul pulsante Salva.
Seleziona la scheda Credenziali, fai clic sul pulsante Crea credenziali
e seleziona ID client OAuth.
Seleziona il tipo di applicazione Altro, inserisci il nome
"Guida rapida all'API YouTube Data" e fai clic sul pulsante Crea.
Fai clic su Ok per chiudere la finestra di dialogo risultante.
Fai clic sul pulsante file_download
(Scarica JSON) a destra dell'ID client.
Sposta il file scaricato nella directory di lavoro e rinominalo
client_secret.json.
Passaggio 2: installa la libreria client
Esegui questi comandi per installare le librerie utilizzando npm:
Crea un file denominato quickstart.js nella directory di lavoro e copia il seguente codice:
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);}});}
La prima volta che esegui l'esempio, ti verrà chiesto di autorizzare l'accesso:
Vai all'URL fornito nel browser web.
Se non hai ancora eseguito l'accesso al tuo Account Google, ti verrà chiesto di farlo. Se hai eseguito l'accesso a più Account Google, ti verrà chiesto di selezionarne uno da utilizzare per l'autorizzazione.
Fai clic sul pulsante Accetta.
Copia il codice che ti viene fornito, incollalo nel prompt della riga di comando e premi
Invio.
Note
Le informazioni di autorizzazione vengono archiviate nel file system, quindi le esecuzioni successive non richiederanno l'autorizzazione.
Il flusso di autorizzazione in questo esempio è progettato per un'applicazione
a riga di comando. Per informazioni su come eseguire l'autorizzazione in un'applicazione web che utilizza l'API YouTube Data, consulta l'articolo sull'utilizzo di OAuth 2.0 per applicazioni server web.
Per informazioni su come eseguire l'autorizzazione in altri contesti, consulta la sezione
Authorizing and Authenticating
del file README della libreria.
[null,null,["Ultimo aggiornamento 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)"]]