快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。本快速入门使用一种简化的身份验证方法,该方法适用于测试环境。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据。
创建一个向 Drive Labels API 发出请求的 Python 命令行应用。
目标
- 设置环境。
- 安装客户端库。
- 设置示例。
- 运行示例。
前提条件
- Python 2.6 或更高版本
- pip 软件包管理工具
- Google Cloud 项目。
- Google 账号。
设置环境
如需完成本快速入门,请设置您的环境。
启用 API
在使用 Google API 之前,您需要在 Google Cloud 项目中将其开启。 您可以在单个 Google Cloud 项目中启用一个或多个 API。- 在 Google Cloud 控制台中,启用 Drive Labels API。 
为桌面应用授权凭据
如需对最终用户进行身份验证并访问应用中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,您必须为每个平台分别创建客户端 ID。- 在 Google Cloud 控制台中,依次前往“菜单”图标 > Google Auth platform > 客户端。
- 点击创建客户端。
- 依次点击应用类型 > 桌面应用。
- 在名称字段中,输入凭据的名称。此名称仅在 Google Cloud 控制台中显示。
- 点击创建。
  新创建的凭据会显示在“OAuth 2.0 客户端 ID”下。 
- 将下载的 JSON 文件另存为 credentials.json,然后将该文件移动到您的工作目录。
安装 Google 客户端库
- 安装 Python 版 Google 客户端库: - pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
如需了解其他安装选项,请参阅 Python 库的安装部分。
配置示例
- 在工作目录中,创建一个名为 quickstart.py的文件。
- 在 - quickstart.py中添加以下代码:- import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly'] def main(): """Shows basic usage of the Drive Labels API. Prints the first page of the customer's Labels. """ creds = None # 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. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) try: service = build('drivelabels', 'v2', credentials=creds) response = service.labels().list( view='LABEL_VIEW_FULL').execute() labels = response['labels'] if not labels: print('No Labels') else: for label in labels: name = label['name'] title = label['properties']['title'] print(u'{0}:\t{1}'.format(name, title)) except HttpError as error: # TODO (developer) - Handle errors from Labels API. print(f'An error occurred: {error}') if __name__ == '__main__': main()
运行示例
- 在工作目录中,构建并运行示例: - python quickstart.py
- 首次运行该示例时,系统会提示您授权访问: - 如果您尚未登录 Google 账号,系统会提示您登录。如果您登录了多个账号,请选择一个账号用于授权。
- 点击接受。
 - 授权信息存储在文件系统中,因此下次运行示例代码时,系统不会提示您进行授权。 
您已成功创建第一个向 Drive Labels API 发出请求的 Python 应用。