googleapis/google-api-nodejs-client
GitHub: googleapis/google-api-nodejs-client
这是Google官方支持的Node.js客户端库,用于简化与Google APIs的交互和认证过程。
Stars: 12166 | Forks: 2020

# Google APIs Node.js 客户端
[][npm]
[][downloads]
[][snyk-url]
* [Google APIs](#google-apis)
* [快速入门](#getting-started)
* [安装说明](#installation)
* [使用客户端库](#using-the-client-library)
* [示例](#samples)
* [API 参考](#api-reference)
* [认证与授权](#authentication-and-authorization)
* [OAuth2 客户端](#oauth2-client)
* [使用 API 密钥](#using-api-keys)
* [应用默认凭据](#application-default-credentials)
* [服务账户凭据](#service-account-credentials)
* [设置全局或服务级别认证](#setting-global-or-service-level-auth)
* [用法](#usage)
* [指定请求正文](#specifying-request-body)
* [媒体上传](#media-uploads)
* [请求选项](#request-options)
* [使用代理](#using-a-proxy)
* [支持的 API](#getting-supported-apis)
* [TypeScript](#typescript)
* [HTTP/2](#http2)
* [许可证](#license)
* [参与贡献](#contributing)
* [有问题/困难?](#questionsproblems)
## Google API
支持的完整 API 列表可以在 [Google APIs Explorer][apiexplorer] 上找到。API 端点是自动生成的,因此如果该 API 不在列表中,则表示此 API 客户端库当前不支持它。
### 使用 Google Cloud Platform API?
当使用如 Datastore、Cloud Storage 或 Pub/Sub 等 Google Cloud Platform API 时,建议使用 @google-cloud 客户端库。这些库是专为特定 Google Cloud Platform 服务设计的、符合 Node.js 习惯的客户端。我们建议安装单独的 API 包,例如 `@google-cloud/storage`。要查看 Google Cloud Platform API 特定包的完整列表,请参阅 https://cloud.google.com/nodejs/docs/reference。
## 快速入门
### 安装说明
此库通过 `npm` 分发。要将其添加为依赖项,请在终端中运行以下命令:
```
npm install googleapis
```
如果需要减少启动时间,您也可以将子模块安装为自己的依赖项。我们努力发布那些 __不在__ 此[列表](https://github.com/googleapis/google-cloud-node#google-cloud-nodejs-client-libraries)中的子模块。要将其添加为依赖项,请在终端中运行以下示例命令,将 `API_NAME` 替换为您偏好的 API:
```
npm install @googleapis/docs
```
您可以在 `npm` 上运行[此搜索](https://www.npmjs.com/search?q=scope%3A@googleapis),以查找可用的子模块列表。
### 使用客户端库
这是一个非常简单的示例。它创建一个 Blogger 客户端,并根据博客 ID 检索博客的详细信息:
```
const {google} = require('googleapis');
// Each API may support multiple versions. With this sample, we're getting
// v3 of the blogger API, and using an API key to authenticate.
const blogger = google.blogger({
version: 'v3',
auth: 'YOUR API KEY'
});
const params = {
blogId: '3213900'
};
// get the blog details
blogger.blogs.get(params, (err, res) => {
if (err) {
console.error(err);
throw err;
}
console.log(`The blog url is ${res.data.url}`);
});
```
除了使用回调,您也可以使用 promises!
```
blogger.blogs.get(params)
.then(res => {
console.log(`The blog url is ${res.data.url}`);
})
.catch(error => {
console.error(error);
});
```
或者使用 async/await:
```
async function runSample() {
const res = await blogger.blogs.get(params);
console.log(`The blog url is ${res.data.url}`);
}
runSample().catch(console.error);
```
或者,您可以通过安装子模块直接调用 API:
```
const docs = require('@googleapis/docs')
const auth = new docs.auth.GoogleAuth({
keyFilename: 'PATH_TO_SERVICE_ACCOUNT_KEY.json',
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: ['https://www.googleapis.com/auth/documents']
});
const authClient = await auth.getClient();
const client = await docs.docs({
version: 'v1',
auth: authClient
});
const createResponse = await client.documents.create({
requestBody: {
title: 'Your new document!',
},
});
console.log(createResponse.data);
```
### 示例
有很多[示例](https://github.com/googleapis/google-api-nodejs-client/tree/main/samples) 🤗。如果您想了解如何使用某个 API... 请先查看那里!您还可以在 cloud.google.com 上搜索特定 API 的 REST 文档,以及嵌入在源代码注释中的文档(位于 src/apis/api-name/version 下)。
### API 参考
此库拥有完整的 [API 参考文档](https://googleapis.dev/nodejs/googleapis/latest)。此文档是自动生成的,其位置可能会更改。
## 认证与授权
- **OAuth2** - 这允许您代表特定用户进行 API 调用。在此模型中,用户访问您的应用程序,使用其 Google 帐户登录,并向您的应用程序授予一组作用域的授权。[了解更多](#oauth2-client)。
- **API 密钥** - 使用 API 密钥,您可以从客户端或服务器访问您的服务。通常安全性较低,仅适用于作用域有限的少数服务子集。[了解更多](#using-api-keys)。
- **应用默认凭据** - 使用 [Google Cloud SDK](https://cloud.google.com/sdk/) 进行本地开发,或使用 [GCE Metadata Server](https://cloud.google.com/compute/docs/storing-retrieving-metadata) 为部署到 Google Cloud Platform 的应用程序提供自动访问 Google API 的权限。[了解更多](#application-default-credentials)。
- **服务账户凭据** - 在此模型中,您的应用程序使用服务账户直接与 Google API 通信。当您有一个后端应用程序需要从后端直接与 Google API 通信时,这非常有用。[了解更多](#service-account-credentials)。
要了解有关认证客户端的更多信息,请参阅 [Google Auth Library](https://github.com/googleapis/google-auth-library-nodejs)。
### OAuth2 客户端
此模块附带一个 [OAuth2][oauth] 客户端,它允许您无缝地获取访问令牌、刷新令牌并重试请求。Google OAuth2 实现的基础知识在 [Google Authorization and Authentication 文档][authdocs] 中有解释。
在以下示例中,您可能需要 `CLIENT_ID`、`CLIENT_SECRET` 和 `REDIRECT_URL`。您可以通过转到[开发者控制台][devconsole],点击您的项目 --> APIs & auth --> 凭据 来找到这些信息。
- 导航到 Cloud 控制台并[创建新的 OAuth2 Client ID](https://console.cloud.google.com/apis/credentials/oauthclient)
- 为应用类型选择 `Web Application`
- 添加授权重定向 URI,值为 `http://localhost:3000/oauth2callback`(或适用于您场景的值)
- 点击 `创建`,并在下一个屏幕上点击 `确定`
- 点击您新创建的 OAuth2 Client ID 旁边的 `下载` 图标
请确保将此文件存储在安全位置,并且*不要将此文件检入源代码控制!*
有关 OAuth2 及其工作原理的更多信息,[请参见此处][oauth]。
一个使用 OAuth2 客户端进行授权和认证的完整示例应用程序可在 [`samples/oauth2.js`][oauthexample] 中找到。
#### 生成认证 URL
要向用户请求权限以获取访问令牌,您需要将其重定向到同意页面。要创建同意页面 URL:
```
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
// generate a url that asks permissions for Blogger and Google Calendar scopes
const scopes = [
'https://www.googleapis.com/auth/blogger',
'https://www.googleapis.com/auth/calendar'
];
const url = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
// If you only need one scope, you can pass it as a string
scope: scopes
});
```
**重要提示** - `refresh_token` 仅在首次授权时返回。更多详情请见[此处](https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450)。
#### 获取授权码
用户在同意页面授予权限后,Google 会将页面重定向到您提供的重定向 URL,并附带一个 `code` 查询参数。
```
GET /oauthcallback?code={authorizationCode}
```
#### 获取访问令牌
有了返回的代码,您就可以按如下方式请求访问令牌:
```
// This will provide an object with the access_token and refresh_token.
// Save these somewhere safe so they can be used at a later time.
const {tokens} = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens);
```
在 OAuth2 客户端上设置好凭据后,您就可以开始了!
#### 处理刷新令牌
访问令牌会过期。此库会自动使用刷新令牌在访问令牌即将过期时获取新的访问令牌。确保您始终存储最新令牌的一个简单方法是使用 `tokens` 事件:
```
oauth2Client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
```
此 `tokens` 事件仅在首次授权时发生,并且您需要在调用 `generateAuthUrl` 方法时将 `access_type` 设置为 `offline` 才能接收刷新令牌。如果您之前已授予应用必要的权限但未设置接收刷新令牌的适当约束条件,您将需要重新授权应用以获取新的刷新令牌。您可以[在此处](https://myaccount.google.com/permissions)撤销应用对您帐户的访问权限。
要在稍后时间设置 `refresh_token`,您可以使用 `setCredentials` 方法:
```
oauth2Client.setCredentials({
refresh_token: `STORED_REFRESH_TOKEN`
});
```
一旦客户端拥有刷新令牌,访问令牌将在下次调用 API 时自动获取和刷新。
刷新令牌在授予后可能会停止工作,原因可能是:
- 用户撤销了您应用的访问权限
- 刷新令牌在 6 个月内未被使用
- 用户更改了密码,并且刷新令牌包含 Gmail 作用域
- 用户帐户超过了活动刷新令牌的最大数量
- 应用状态为“测试”,且同意屏幕配置为外部用户类型,导致令牌在 7 天后过期
作为开发人员,您应编写代码来处理刷新令牌不再工作的情况。
### 使用 API 密钥
您可能需要在即将发出的请求中发送 API 密钥。以下示例使用 API 密钥向 Blogger API 服务发出请求,以检索博客的名称、URL 及其帖子总数:
```
const {google} = require('googleapis');
const blogger = google.blogger_v3({
version: 'v3',
auth: 'YOUR_API_KEY' // specify your API key here
});
const params = {
blogId: '3213900'
};
async function main(params) {
const res = await blogger.blogs.get({blogId: params.blogId});
console.log(`${res.data.name} has ${res.data.posts.totalItems} posts! The blog url is ${res.data.url}`)
};
main().catch(console.error);
```
要了解有关 API 密钥的更多信息,请参阅[文档][usingkeys]。
#### 应用默认凭据
与其手动创建 OAuth2 客户端、JWT 客户端或 Compute 客户端,认证库可以根据代码运行的环境为您创建正确的凭据类型。
例如,当代码在本地开发机器上运行时,将创建 JWT 认证客户端;当相同的代码在已配置的 Google Compute Engine 实例上运行时,将创建 Compute 客户端。下面的代码演示了如何根据运行时环境检索默认凭据类型。
要在本地使用 [Google Cloud SDK](https://cloud.google.com/sdk/) 的应用默认凭据,请运行:
```
$ gcloud auth application-default login
```
在 GCP 中运行时,服务授权通过 GCE Metadata 服务器自动提供。
```
const {google} = require('googleapis');
const compute = google.compute('v1');
async function main () {
const auth = new google.auth.GoogleAuth({
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: ['https://www.googleapis.com/auth/compute']
});
const authClient = await auth.getClient();
// obtain the current project Id
const project = await auth.getProjectId();
// Fetch the list of GCE zones within a project.
const res = await compute.zones.list({ project, auth: authClient });
console.log(res.data);
}
main().catch(console.error);
```
### 服务账户凭据
服务账户允许您使用机器人帐户执行服务器到服务器、应用级别的身份验证。您将创建一个服务帐户,下载一个密钥文件,并使用它来对 Google API 进行身份验证。要创建服务帐户:
- 前往[创建服务帐户密钥页面](https://console.cloud.google.com/apis/credentials/serviceaccountkey)
- 在下拉菜单中选择 `New Service Account`
- 点击 `创建` 按钮
将服务帐户凭据文件保存在安全位置,并且*不要将此文件检入源代码控制!* 要引用服务帐户凭据文件,您有几种选择。
#### 使用 `GOOGLE_APPLICATION_CREDENTIALS` 环境变量
您可以使用名为 `GOOGLE_APPLICATION_CREDENTIALS` 的环境变量启动进程。此环境变量的值应为服务帐户凭据文件的完整路径:
```
$ GOOGLE_APPLICATION_CREDENTIALS=./your-secret-key.json node server.js
```
#### 使用 `keyFile` 属性
或者,您可以通过 `GoogleAuth` 构造函数中的 `keyFile` 属性指定服务帐户凭据文件的路径:
```
const {google} = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFile: '/path/to/your-secret-key.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
```
### 设置全局或服务级别认证
您可以将 `auth` 设置为全局或服务级别的选项,这样您就不需要在每个请求中都指定它。例如,您可以将 `auth` 设置为全局选项:
```
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
// set auth as a global default
google.options({
auth: oauth2Client
});
```
除了全局设置选项外,您还可以在服务级别设置认证客户端:
```
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
const drive = google.drive({
version: 'v2',
auth: oauth2Client
});
```
更多信息请参阅[选项部分](#request-options)。
## 用法
### 指定请求正文
请求的正文在请求的 `requestBody` 参数对象中指定。正文被指定为具有键/值对的 JavaScript 对象。例如,此示例创建一个观察程序,当邮件发送到 Gmail 帐户时,将通知发布到 Google Cloud Pub/Sub 主题:
```
const res = await gmail.users.watch({
userId: 'me',
requestBody: {
// Replace with `projects/${PROJECT_ID}/topics/${TOPIC_NAME}`
topicName: `projects/el-gato/topics/gmail`
}
});
console.log(res.data);
```
### 请求选项
为了对 API 调用的方式进行更精细的控制,我们为您提供了指定附加选项的能力,这些选项可以直接应用于此库中用于进行 API 网络调用的 ['gaxios'][gaxios] 对象。
您可以在全局 `google` 对象或服务客户端基础上指定附加选项。您指定的选项会附加到 `gaxios` 对象,因此 `gaxios` 支持的任何选项,此库都支持。您还可以指定全局或每个服务的请求参数,这些参数将附加到您发出的所有 API 调用中。
支持的完整选项列表可以[在此处找到](https://github.com/googleapis/gaxios/#request-options)。
#### 全局选项
您可以选择将随每个请求发送的默认选项。这些选项将用于由 google 客户端实例化的每个服务。在此示例中,`GaxiosOptions` 的 `timeout` 属性将针对每个请求进行设置:
```
const {google} = require('googleapis');
google.options({
// All requests made with this object will use these settings unless overridden.
timeout: 1000,
auth: auth
});
```
您还可以修改随每个请求发送的参数:
```
const {google} = require('googleapis');
google.options({
// All requests from all services will contain the above query parameter
// unless overridden either in a service client or in individual API calls.
params: {
quotaUser: 'user123@example.com'
}
});
```
#### 服务客户端选项
您也可以在创建服务客户端时指定选项。
```
const blogger = google.blogger({
version: 'v3',
// All requests made with this object will use the specified auth.
auth: 'API KEY';
});
```
通过这样做,使用此服务客户端进行的每个 API 调用都将使用 `'API KEY'` 进行身份验证。
**注意:** 创建的客户端是**不可变的**,因此如果您想指定不同的选项,必须创建一个新客户端。
与上面的示例类似,您也可以修改用于给定服务的每次调用的参数:
```
const blogger = google.blogger({
version: 'v3',
// All requests made with this service client will contain the
// blogId query parameter unless overridden in individual API calls.
params: {
blogId: '3213900'
}
});
// Calls with this drive client will NOT contain the blogId query parameter.
const drive = google.drive('v3');
...
```
#### 请求级别选项
您可以指定一个 `auth` 对象用于每个请求。每个请求也会继承在服务级别和全局级别指定的选项。
例如:
```
const {google} = require('googleapis');
const bigquery = google.bigquery('v2');
async function main() {
// This method looks for the GCLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
// environment variables.
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
const authClient = await auth.getClient();
const projectId = await auth.getProjectId();
const request = {
projectId,
datasetId: '
',
// This is a "request-level" option
auth: authClient
};
const res = await bigquery.datasets.delete(request);
console.log(res.data);
}
main().catch(console.error);
```
您还可以覆盖每个请求的 *gaxios* 选项,例如 `url`、`method` 和 `responseType`。
例如:
```
const res = await drive.files.export({
fileId: 'asxKJod9s79', // A Google Doc
mimeType: 'application/pdf'
}, {
// Make sure we get the binary data
responseType: 'stream'
});
```
### 使用代理
您可以使用以下环境变量来代理 HTTP 和 HTTPS 请求:
- `HTTP_PROXY` / `http_proxy`
- `HTTPS_PROXY` / `https_proxy`
当设置了 HTTP_PROXY / http_proxy 时,它们将用于代理没有显式代理配置选项存在的非 SSL 请求。类似地,HTTPS_PROXY / https_proxy 将用于没有显式代理配置选项的 SSL 请求。可以在其中一个环境变量中定义代理,然后使用代理配置选项为特定请求覆盖它。
### 获取支持的 API
您可以通过编程方式获取支持的 API 列表以及所有可用版本:
```
const {google} = require('googleapis');
const apis = google.getSupportedAPIs();
```
这将返回一个对象,其中 API 名称作为对象属性名称,版本字符串数组作为对象值;
### TypeScript
此库使用 TypeScript 编写,并提供开箱即用的类型。为每个 API 生成的所有类和接口都在 `${apiName}_${version}` 命名空间下导出。例如,Drive v3 API 类型都可以从 `drive_v3` 命名空间中获取:
```
import {
google, // The top level object used to access services
drive_v3, // For every service client, there is an exported namespace
Auth, // Namespace for auth related types
Common, // General types used throughout the library
} from 'googleapis';
// Note: using explicit types like `Auth.GoogleAuth` are only here for
// demonstration purposes. Generally with TypeScript, these types would
// be inferred.
const auth: Auth.GoogleAuth = new google.auth.GoogleAuth();
const drive: drive_v3.Drive = google.drive({
version: 'v3',
auth,
});
// There are generated types for every set of request parameters
const listParams: drive_v3.Params$Resource$Files$List = {};
const res = await drive.files.list(listParams);
// There are generated types for the response fields as well
const listResults: drive_v3.Schema$FileList = res.data;
```
### HTTP/2
```
const {google} = require('googleapis');
google.options({
http2: true,
});
```
## 发布说明及重大变更
您可以在我们的[发布说明][releasenotes]中找到重大变更和新功能的详细列表。如果您之前使用过 `25.x` 之前的版本,请参阅我们的[发布说明][releasenotes],了解如何将代码从 `24.x.x` 迁移到 `25.x.x`。这非常简单 :)
## 许可证
此库根据 Apache 2.0 许可证获得许可。完整许可证文本可在 [LICENSE][license] 中找到。
## 有问题/困难?
* 在 [Stackoverflow][stackoverflow] 上提出与开发相关的问题。
* 如果您发现了错误/问题,请[在 GitHub 上提交][bugs]。
标签:API哈希动态解析, API密钥, Google APIs访问, Google Cloud Platform, HTTP/2支持, JWT令牌, MITM代理, Node.js客户端库, npm包, OAuth 2.0, SOC Prime, Streamlit, TypeScript支持, Web API, 云服务集成, 安全认证, 客户端库, 开发工具, 数据可视化, 暗色界面, 自动化攻击, 认证授权, 访问控制