快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。
Google Workspace 快速入门使用 API 客户端库来处理身份验证和授权流程的一些细节。我们建议您将客户端库用于自己的应用。本快速入门使用适合测试环境的简化身份验证方法。对于生产环境,我们建议您先了解身份验证和授权,然后再为您的应用选择访问凭据。
创建一个向 Drive Label API 发出请求的 Node.js 命令行应用。
目标
- 设置环境。
- 安装客户端库。
- 设置示例。
- 运行该示例。
前提条件
- 已安装 Node.js 和 npm。
- Google Cloud 项目。
- Google 帐号。
设置您的环境
如需完成本快速入门,请设置您的环境。
启用 API
在使用 Google API 之前,您需要先在 Google Cloud 项目中启用这些 API。您可以在单个 Google Cloud 项目中启用一个或多个 API。在 Google Cloud 控制台中,启用 Drive Label API。
为桌面应用授权凭据
如需对最终用户进行身份验证并访问应用中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,您必须为每个平台创建一个单独的客户端 ID。- 在 Google Cloud 控制台中,依次点击“菜单”图标 > API 和服务 > 凭据。
- 依次点击创建凭据 > OAuth 客户端 ID。
- 依次点击应用类型 > 桌面应用。
- 在名称字段中,输入凭据的名称。此名称仅在 Google Cloud 控制台中显示。
- 点击创建。系统会显示“OAuth 客户端创建”屏幕,其中显示了您的新客户端 ID 和客户端密钥。
- 点击 OK。新创建的凭据会显示在 OAuth 2.0 客户端 ID 下。
- 将下载的 JSON 文件另存为
credentials.json
,并将该文件移动到您的工作目录。
安装客户端库
使用 npm 安装库:
npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
设置示例
在您的工作目录中,创建一个名为
index.js
的文件。在该文件中,粘贴以下代码:
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'); } }); }
运行示例
在您的工作目录中,运行该示例:
node .
首次运行该示例时,它会提示您授予访问权限:
- 如果您尚未登录 Google 帐号,系统会提示您登录。如果您登录了多个帐号,请选择一个用于授权的帐号。
- 点击接受。
授权信息存储在文件系统中,因此下次运行示例代码时,系统不会提示您进行授权。
您已成功创建了第一个向 Drive Label API 发出请求的 Nodejs 应用。