Stay organized with collections
Save and categorize content based on your preferences.
Quickstarts explain how to set up and run an app that calls a
Google Workspace API. This quickstart uses a
simplified authentication approach that is appropriate for a testing
environment. For a production environment, we recommend learning about
authentication and authorization
before
choosing the access credentials
that are appropriate for your app.
Create a Node.js command-line application that makes requests to the
Drive Labels API.
To authenticate end users and access user data in your app, you need to
create one or more OAuth 2.0 Client IDs. A client ID is used to identify a
single app to Google's OAuth servers. If your app runs on multiple platforms,
you must create a separate client ID for each platform.
In the Google Cloud console, go to Menu menu>Google Auth platform>Clients.
In your working directory, create a file named index.js.
In the file, paste the following code:
constfs=require('fs');constreadline=require('readline');const{google}=require('googleapis');// If modifying these scopes, delete token.json.constSCOPES=['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.constTOKEN_PATH='token.json';// Load client secrets from a local file.fs.readFile('credentials.json',(err,content)=>{if(err)returnconsole.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. */functionauthorize(credentials,callback){const{client_secret,client_id,redirect_uris}=credentials.installed;constoAuth2Client=newgoogle.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)returngetNewToken(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. */functiongetNewToken(oAuth2Client,callback){constauthUrl=oAuth2Client.generateAuthUrl({access_type:'offline',scope:SCOPES,});console.log('Authorize this app by visiting this url:',authUrl);constrl=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)returnconsole.error('Error retrieving access token',err);oAuth2Client.setCredentials(token);// Store the token to disk for later program executionsfs.writeFile(TOKEN_PATH,JSON.stringify(token),(err)=>{if(err)returnconsole.error(err);console.log('Token stored to',TOKEN_PATH);});callback(oAuth2Client);});});}functionlistDriveLabels(auth){constservice=google.drivelabels({version:'v2',auth});constparams={'view':'LABEL_VIEW_FULL'};service.labels.list(params,(err,res)=>{if(err)returnconsole.error('The API returned an error: '+err);constlabels=res.data.labels;if(labels){labels.forEach((label)=>{constname=label.name;consttitle=label.properties.title;console.log(`${name}\t${title}`);});}else{console.log('No Labels');}});}
Run the sample
In your working directory, run the sample:
node .
The first time you run the sample, it prompts you to authorize access:
If you're not already signed in to your Google Account, you're
prompted to sign in. If you're signed in to multiple accounts,
select one account to use for authorization.
Click Accept.
Authorization information is stored in the file system, so the next time you
run the sample code, you aren't prompted for authorization.
You have successfully created your first Nodejs application that makes requests
to the Drive Labels API.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-28 UTC."],[],[],null,["Quickstarts explain how to set up and run an app that calls a\nGoogle Workspace API. This quickstart uses a\nsimplified authentication approach that is appropriate for a testing\nenvironment. For a production environment, we recommend learning about\n[authentication and authorization](/workspace/guides/auth-overview)\nbefore\n[choosing the access credentials](/workspace/guides/create-credentials#choose_the_access_credential_that_is_right_for_you)\nthat are appropriate for your app.\n\nCreate a Node.js command-line application that makes requests to the\nDrive Labels API.\n\nObjectives\n\n- Set up your environment.\n- Install the client library.\n- Set up the sample.\n- Run the sample.\n\nPrerequisites\n\n- [Node.js \\& npm](https://docs.npmjs.com/getting-started/installing-node#1-install-nodejs--npm) installed.\n- [A Google Cloud project](/workspace/guides/create-project).\n\n\u003c!-- --\u003e\n\n- A Google Account.\n\nSet up your environment\n\nTo complete this quickstart, set up your environment.\n\nEnable the API Before using Google APIs, you need to turn them on in a Google Cloud project. You can turn on one or more APIs in a single Google Cloud project.\n\n- In the Google Cloud console, enable the Drive Labels API.\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=drivelabels.googleapis.com)\n\nAuthorize credentials for a desktop application To authenticate end users and access user data in your app, you need to create one or more OAuth 2.0 Client IDs. A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms, you must create a separate client ID for each platform. **Caution:** This quickstart must be run locally and with access to a browser. It doesn't work if run on a remote terminal such as Cloud Shell or over SSH.\n\n1. In the Google Cloud console, go to Menu menu \\\u003e **Google Auth platform** \\\u003e **Clients** .\n\n [Go to Clients](https://console.cloud.google.com/auth/clients)\n2. Click **Create Client**.\n3. Click **Application type** \\\u003e **Desktop app**.\n4. In the **Name** field, type a name for the credential. This name is only shown in the Google Cloud console.\n5. Click **Create** .\n\n\n The newly created credential appears under \"OAuth 2.0 Client IDs.\"\n6. Save the downloaded JSON file as `credentials.json`, and move the file to your working directory.\n\nInstall the client library\n\n- Install the libraries using npm:\n\n ```\n npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save\n ```\n\nSet up the sample\n\n1. In your working directory, create a file named `index.js`.\n\n2. In the file, paste the following code:\n\n \u003cbr /\u003e\n\n const fs = require('fs');\n const readline = require('readline');\n const {google} = require('googleapis');\n\n // If modifying these scopes, delete token.json.\n const SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly'];\n // The file token.json stores the user's access and refresh tokens, and is\n // created automatically when the authorization flow completes for the first\n // time.\n const TOKEN_PATH = 'token.json';\n\n // Load client secrets from a local file.\n fs.readFile('credentials.json', (err, content) =\u003e {\n if (err) return console.log('Error loading client secret file:', err);\n // Authorize a client with credentials, then call the Google Drive Labels\n // API.\n authorize(JSON.parse(content), listDriveLabels);\n });\n\n /**\n * Create an OAuth2 client with the given credentials, and then execute the\n * given callback function.\n * @param {Object} credentials The authorization client credentials.\n * @param {function} callback The callback to call with the authorized client.\n */\n function authorize(credentials, callback) {\n const {client_secret, client_id, redirect_uris} = credentials.installed;\n const oAuth2Client = new google.auth.OAuth2(\n client_id, client_secret, redirect_uris[0]);\n\n // Check if we have previously stored a token.\n fs.readFile(TOKEN_PATH, (err, token) =\u003e {\n if (err) return getNewToken(oAuth2Client, callback);\n oAuth2Client.setCredentials(JSON.parse(token));\n callback(oAuth2Client);\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 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.\n * @param {getEventsCallback} callback The callback for the authorized client.\n */\n function getNewToken(oAuth2Client, callback) {\n const authUrl = oAuth2Client.generateAuthUrl({\n access_type: 'offline',\n scope: SCOPES,\n });\n console.log('Authorize this app by visiting this url:', authUrl);\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question('Enter the code from that page here: ', (code) =\u003e {\n rl.close();\n oAuth2Client.getToken(code, (err, token) =\u003e {\n if (err) return console.error('Error retrieving access token', err);\n oAuth2Client.setCredentials(token);\n // Store the token to disk for later program executions\n fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) =\u003e {\n if (err) return console.error(err);\n console.log('Token stored to', TOKEN_PATH);\n });\n callback(oAuth2Client);\n });\n });\n }\n\n function listDriveLabels(auth) {\n const service = google.drivelabels({version: 'v2', auth});\n const params = {\n 'view': 'LABEL_VIEW_FULL'\n };\n service.labels.list(params, (err, res) =\u003e {\n if (err) return console.error('The API returned an error: ' + err);\n const labels = res.data.labels;\n if (labels) {\n labels.forEach((label) =\u003e {\n const name = label.name;\n const title = label.properties.title;\n console.log(`${name}\\t${title}`);\n });\n } else {\n console.log('No Labels');\n }\n });\n }\n\nRun the sample\n\n1. In your working directory, run the sample:\n\n ```\n node .\n ```\n2. The first time you run the sample, it prompts you to authorize access:\n\n 1. If you're not already signed in to your Google Account, you're prompted to sign in. If you're signed in to multiple accounts, select one account to use for authorization.\n 2. Click **Accept**.\n\n Authorization information is stored in the file system, so the next time you\n run the sample code, you aren't prompted for authorization.\n\nYou have successfully created your first Nodejs application that makes requests\nto the Drive Labels API.\n\nNext steps\n\n- [Troubleshoot authentication and authorization issues](/workspace/drive/labels/troubleshoot-authentication-authorization)\n- [Google APIs Node.js Client section on GitHub](https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client)."]]