Le rapide spiegano come configurare ed eseguire un'app che chiama un'API Google Workspace.
I comandi iniziali di Google Workspace utilizzano le librerie client API per gestire alcuni dettagli del flusso di autenticazione e autorizzazione. Ti consigliamo di utilizzare le librerie client per le tue app. Questa guida rapida utilizza un approccio di autenticazione semplificato appropriato per un ambiente di test. Per un ambiente di produzione, ti consigliamo di informarti sull'autenticazione e sull'autorizzazione prima di scegliere le credenziali di accesso appropriate per la tua app.
Crea un'applicazione a riga di comando Node.js che invii richieste all'API Etichette di Drive.
Obiettivi
- Configurare l'ambiente.
- Installa la libreria client.
- Configura il Sample.
- Esegui il sample.
Prerequisiti
- Node.js e npm installati.
- Un progetto Google Cloud.
- Un Account Google.
Configura l'ambiente
Per completare questa guida rapida, configura l'ambiente.
Abilita l'API
Prima di utilizzare le API Google, devi attivarle in un progetto Google Cloud. Puoi attivare una o più API in un singolo progetto Google Cloud.Nella console Google Cloud, abilita l'API Drive Labels.
Autorizzare le credenziali per un'applicazione desktop
Per autenticare gli utenti finali e accedere ai dati utente nella tua app, devi creare uno o più ID client OAuth 2.0. L'ID client viene utilizzato per identificare una singola app nei server OAuth di Google. Se l'app viene eseguita su più piattaforme, devi creare un ID client separato per ogni piattaforma.- Nella console Google Cloud, vai a Menu > > Client.
- Fai clic su Crea cliente.
- Fai clic su Tipo di applicazione > App desktop.
- Nel campo Nome, digita un nome per la credenziale. Questo nome viene visualizzato solo nella console Google Cloud.
- Fai clic su Crea.
La credenziale appena creata viene visualizzata in "ID client OAuth 2.0".
- Salva il file JSON scaricato come
credentials.json
e spostalo nella directory di lavoro.
installa la libreria client
Installa le librerie utilizzando npm:
npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
Configura il Sample
Nella directory di lavoro, crea un file denominato
index.js
.Nel file, incolla il seguente codice:
const fs = require('fs'); const readline = require('readline'); const {google} = require('googleapis'); // If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly']; // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. const TOKEN_PATH = 'token.json'; // Load client secrets from a local file. fs.readFile('credentials.json', (err, content) => { if (err) return console.log('Error loading client secret file:', err); // Authorize a client with credentials, then call the Google Drive Labels // API. authorize(JSON.parse(content), listDriveLabels); }); /** * 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) { const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getNewToken(oAuth2Client, callback); oAuth2Client.setCredentials(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 for the authorized client. */ function getNewToken(oAuth2Client, callback) { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES, }); console.log('Authorize this app by visiting this url:', authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('Enter the code from that page here: ', (code) => { rl.close(); oAuth2Client.getToken(code, (err, token) => { if (err) return console.error('Error retrieving access token', err); oAuth2Client.setCredentials(token); // Store the token to disk for later program executions fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { if (err) return console.error(err); console.log('Token stored to', TOKEN_PATH); }); callback(oAuth2Client); }); }); } function listDriveLabels(auth) { const service = google.drivelabels({version: 'v2', auth}); const params = { 'view': 'LABEL_VIEW_FULL' }; service.labels.list(params, (err, res) => { if (err) return console.error('The API returned an error: ' + err); const labels = res.data.labels; if (labels) { labels.forEach((label) => { const name = label.name; const title = label.properties.title; console.log(`${name}\t${title}`); }); } else { console.log('No Labels'); } }); }
Esegui il sample
Nella directory di lavoro, esegui il sample:
node .
La prima volta che esegui il sample, ti viene chiesto di autorizzare l'accesso:
- Se non hai ancora eseguito l'accesso al tuo Account Google, ti verrà chiesto di farlo. Se hai eseguito l'accesso a più account, selezionane uno da utilizzare per l'autorizzazione.
- Fai clic su Accept (accetta).
Le informazioni di autorizzazione vengono memorizzate nel file system, quindi la volta successiva che esegui il codice di esempio non ti verrà richiesta l'autorizzazione.
Hai creato la tua prima applicazione Node.js che invia richieste all'API Drive Labels.
Passaggi successivi
- Risolvere i problemi di autenticazione e autorizzazione
- Sezione Client Node.js per le API di Google su GitHub.