使用 gRPC 进行首次 API 调用

1. 简介

Google Health API 支持 gRPC,可实现高性能和低延迟的数据检索。与 REST 不同,使用 gRPC 需要先获取 API 的协议缓冲区 (protobuf) 定义并生成客户端桩代码,然后才能发出请求。

在此 Codelab 中,您将学习如何设置 Python 开发环境、检索公共 API proto 定义、使用协议缓冲区编译器库编译这些定义,以及进行首次 gRPC 调用来检索健康数据。

学习内容

  • 如何在 Google Cloud 控制台中设置客户端 ID。
  • 如何设置 Python 虚拟环境并安装 gRPC 依赖项。
  • 如何获取 Google Health API 协议缓冲区定义。
  • 如何编译 proto 文件以生成客户端代码。
  • 如何通过 Google OAuth 2.0 授权流程获取访问令牌和刷新令牌。
  • 如何使用 Python 向 Google Health API 端点发出 gRPC 调用。

所需条件

  • Google Health 移动应用
  • 系统上安装了 Python 3.8 或更高版本
  • VS Code 或您选择的其他文本编辑器和终端

如要设置 Google Health 移动应用,请按以下步骤操作:

  1. 在 Apple App Store 或 Google Play 商店中,搜索 Google Health 移动应用并下载。
  2. 选择应用图标。
  3. 点击使用 Google 账号登录
  4. 选择您的 Google 账号,然后按继续按钮。

2. 设置 Google Cloud 项目

您将使用 Google Cloud 控制台创建客户端 ID,并启用 Google Health API。

  1. 登录 Google Cloud 控制台。
  2. 如需创建新项目,请执行以下操作:
    1. 在项目选择器中点击选择项目。
    2. 在右上角,选择新建项目。
    3. 输入项目名称。
    4. 输入您的位置(例如“无组织”)。
    5. 点击创建按钮。
    6. 选择您的项目。

启用 Google Health API

  1. 点击左上角的菜单图标:Google Cloud 控制台导航菜单图标
  2. 选择 API 和服务 > 库。
  3. 搜索“Google Health API”并启用。

设置 OAuth 凭证

如果您不在 Google Cloud 控制台中,请前往 Google Cloud 控制台。

  1. 点击左上角的菜单图标:Google Cloud 控制台导航菜单图标
  2. 依次选择 API 和服务 > 凭证。
  3. 在顶部中心位置,依次选择 + 创建凭据 > OAuth 客户端 ID。
  4. 点击配置权限请求页面按钮。如果显示“尚未配置 Google Auth Platform”消息,请点击开始使用按钮。
  5. 在第 1 部分中:
    1. 输入应用名称。
    2. 输入用户支持邮箱。
    3. 点击下一步按钮。
  6. 在第 2 部分中:
    1. 选择外部。
    2. 点击下一步按钮。
  7. 在第 3 部分中:
    1. 在联系信息字段中输入您的邮箱。
    2. 点击下一步按钮。
  8. 在第 4 部分中:
    1. 点击复选框,同意 Google 的 API 服务用户数据政策。
    2. 点击创建按钮。
  9. 返回 API 和服务 > 凭据,然后依次选择 + 创建凭据 > OAuth 客户端 ID。
  10. 选择应用类型桌面应用。
  11. 输入客户端 ID 名称(例如“Google Health API gRPC Codelab”)。
  12. 点击创建按钮。
  13. Google 控制台会显示一条消息,告知您客户端 ID 已创建。点击下载 JSON 链接,下载客户端 ID 和客户端密钥文件。由于浏览器会使用包含您的客户端 ID 的默认名称(例如 client_secret_.json)下载该文件,因此您必须将该文件重命名为 client_secret.json。稍后,我们会将此文件放入代码库中。
  14. 点击确定。您将返回到“OAuth 2.0 客户端 ID”页面。

添加测试用户

  1. 在左侧窗格中,选择受众群体。您应该会看到发布状态设置为测试,用户类型设置为外部。
  2. 在测试用户部分下,点击 + 添加用户按钮。输入您在 Google Health 移动应用中登录的 Google 账号的邮箱。
  3. 点击保存按钮。

向客户端 ID 添加范围

  1. 在左侧窗格中,选择数据访问。
  2. 点击添加或移除范围按钮。
  3. 在“API”列中,搜索“Google Health API”。在此 Codelab 中,我们将使用 https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly 范围
  4. 选择范围后,按更新按钮返回“数据访问”页面。
  5. 点击保存按钮。

您已完成客户端 ID 的设置。

3. 向 Google Health 移动应用添加数据

对于 Google Health API 的新用户,您的 Google Health 账号中可能没有可供查询的数据。我们将手动添加一条锻炼日志,以便通过其中一个端点进行查询。如要手动记录锻炼,请按以下步骤操作:

  1. 在设备上打开 Google Health 移动应用。根据需要登录 Google Health 账号。
  2. 点按屏幕右下角的 + 按钮。
  3. 在手动记录部分,点按活动。
  4. 搜索锻炼类型步行并选择。
  5. 输入今天的开始时间。
  6. 将时长更改为 15 分钟。
  7. 将距离保留为 1.0 英里。
  8. 点按添加。
  9. 长按屏幕并向下滑动,将移动应用同步到 Google Health 服务器。松开手指后,您应该会看到移动应用开始同步。
  10. 在活动部分,你应该会看到手动记录的步行条目。显示步行活动的屏幕截图。

4. 设置 Python 项目和依赖项

我们将设置一个本地工作区目录,并建立一个 Python 虚拟环境来管理此 Codelab 的依赖项。

  1. 打开终端。
  2. 运行适用于您的操作系统的设置命令:
    • 在 macOS/Linux 上:
      mkdir health-grpc-codelab && cd health-grpc-codelab && python3 -m venv venv && source venv/bin/activate && pip install grpcio grpcio-tools google-auth google-auth-oauthlib googleapis-common-protos
      
    • 在 Windows 上(命令提示符):
      mkdir health-grpc-codelab && cd health-grpc-codelab && python3 -m venv venv && venv\Scripts\activate.bat && pip install grpcio grpcio-tools google-auth google-auth-oauthlib googleapis-common-protos
      
    • 在 Windows 上 (PowerShell):
      mkdir health-grpc-codelab; cd health-grpc-codelab; python3 -m venv venv; venv\Scripts\Activate.ps1; pip install grpcio grpcio-tools google-auth google-auth-oauthlib googleapis-common-protos
      
    • grpcio:核心 gRPC 库。
    • grpcio-tools:适用于 Python 的 protobuf 编译器工具链。
    • google-auth / google-auth-oauthlib:用于处理凭据和 OAuth 授权的安全机制。
    • googleapis-common-protos:包含生成的桩文件导入的辅助模块(如 google.api.annotations_pb2)的软件包。
  3. 将您在上一部分中下载并重命名的 client_secret.json 凭证文件移至此父级 health-grpc-codelab 文件夹中。

5. 获取 proto 并生成桩

在通过 gRPC 请求数据之前,我们必须将与 Google Health API 匹配的协议缓冲区 (.proto) 定义编译为客户端桩。

由于架构依赖于各种共享的 Google API 文件(例如注解、操作和字段行为),因此最简单的方法是克隆官方的公开 Google API 代码库。

  1. 克隆 googleapis GitHub 代码库,编译所需的客户端架构,然后一步返回到父级工作区文件夹:
    git clone --depth 1 https://github.com/googleapis/googleapis.git && \
    cd googleapis && \
    python3 -m grpc_tools.protoc \
      --proto_path=. \
      --python_out=. \
      --grpc_python_out=. \
      google/devicesandservices/health/v4/data_points.proto \
      google/devicesandservices/health/v4/data_model.proto \
      google/devicesandservices/health/v4/data_source.proto \
      google/devicesandservices/health/v4/data_coordinates.proto \
      google/devicesandservices/health/v4/medical_device_info.proto && \
    cd ..
    
    这将编译 protobuf 并直接在 googleapis/google/devicesandservices/health/v4/ 子目录中生成 .py 桩文件。

6. 使用 Python 实现 gRPC 客户端代码

为了进行身份验证和请求数据,我们将编写一个脚本。

  1. 在 health-grpc-codelab 目录的根目录下创建一个名为 client.py 的文件。
  2. 使用以下代码填充 client.py:
import sys
# Add the 'googleapis' directory to sys.path so files in it can be imported
sys.path.insert(0, 'googleapis')

import os
import json
import grpc

import google.auth
from google.auth.transport.grpc import secure_authorized_channel
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

# Import compiled gRPC stubs & message modules
from google.devicesandservices.health.v4 import data_points_pb2
from google.devicesandservices.health.v4 import data_points_pb2_grpc
from google.devicesandservices.health.v4 import data_source_pb2
from google.devicesandservices.health.v4 import data_model_pb2

# --- CONFIGURATION ---
CLIENT_SECRETS_FILE = 'client_secret.json'
SCOPES = ['https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly']
TOKEN_FILE = 'token.json'
GRPC_ENDPOINT = 'health.googleapis.com'

def get_credentials():
    """Gets or creates OAuth 2.0 credentials."""
    creds = None
    # Load token from disk if it was already authorized
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'r') as token:
            creds = Credentials.from_authorized_user_info(json.load(token), SCOPES)
    # Refresh token if expired
    if creds and creds.expired and creds.refresh_token:
        try:
            creds.refresh(Request())
        except Exception as e:
            creds = None  # Force re-authentication if refresh fails
    # Run user consent flow if not authorized yet
    if not creds or not creds.valid:
        flow = InstalledAppFlow.from_client_secrets_file(
            CLIENT_SECRETS_FILE, SCOPES
        )
        # Using desktop app loopback mechanism (opens local browser)
        creds = flow.run_local_server(port=0)
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
    return creds

def fetch_health_data_grpc(creds):
    """Fetches health data using gRPC."""
    try:
        # 1. Establish secure, authorized channel using OAuth 2.0 Credentials
        channel = secure_authorized_channel(creds, Request(), f'{GRPC_ENDPOINT}:443')

        # 2. Instantiate the service stub client
        stub = data_points_pb2_grpc.DataPointsServiceStub(channel)

        # 3. Request data points for data type "exercise"
        print("Sending ListDataPoints RPC...")
        request = data_points_pb2.ListDataPointsRequest(parent='users/me/dataTypes/exercise')
        response = stub.ListDataPoints(request)

        # 4. Display result
        print('--- Success ---')
        for dp in response.data_points:
            platform_str = data_source_pb2.DataSource.Platform.Name(dp.data_source.platform)
            exercise_str = data_model_pb2.Exercise.ExerciseType.Name(dp.exercise.exercise_type)

            print(f"Data Point ID: {dp.name}")
            print(f"Platform: {platform_str}")
            print(f"Exercise type: {exercise_str}")
            print(f"Display Name: {dp.exercise.display_name}")
            print(f"Start Time: {dp.exercise.interval.start_time.ToJsonString()}")
            print(f"Calories (kcal): {int(dp.exercise.metrics_summary.calories_kcal)}")
            print(f"Steps: {dp.exercise.metrics_summary.steps}")
            print('----------------')
    except grpc.RpcError as e:
        print(f'gRPC Error: {e.code()} - {e.details()}')
    except Exception as e:
        print(f'General error: {e}')

if __name__ == '__main__':
    try:
        print("Retrieving OAuth 2.0 credentials...")
        creds = get_credentials()
        print("Making gRPC requests...")
        fetch_health_data_grpc(creds)
    except Exception as e:
        print(f"An error occurred: {e}")

代码说明

以下是客户端脚本如何使用 gRPC 与 Google Health API 交互的详细说明:

  • 导入生成的桩(第 1-19 行):首先,脚本会将包含已编译 protobuf 架构 (googleapis/) 的目录添加到系统导入路径。然后,它会导入生成的 Python 模块:
    • data_points_pb2_grpc:包含表示 API 服务的客户端桩 (DataPointsServiceStub)。
    • data_points_pb2 和其他 _pb2 模块:包含请求和响应所使用的消息类(如 ListDataPointsRequest)和数据架构。
  • 建立安全信道(第 54-55 行):
    channel = secure_authorized_channel(creds, Request(), f'{GRPC_ENDPOINT}:443')
    
    在 gRPC 中,通道表示与远程端点的连接。此代码使用 google-auth 库中的 secure_authorized_channel 在端口 443 上建立安全的 TLS 连接,该连接会自动将 OAuth 2.0 授权凭据附加到所有调用元数据。
  • 实例化客户端桩(第 58 行):
    stub = data_points_pb2_grpc.DataPointsServiceStub(channel)
    
    这会实例化一个本地客户端桩(或客户端类),用于表示 Health API 的 DataPointsService 服务定义。您可以通过此桩直接调用所有远程过程。
  • 执行 RPC 调用(第 62-63 行):
    request = data_points_pb2.ListDataPointsRequest(parent='users/me/dataTypes/exercise')
    response = stub.ListDataPoints(request)
    
    您需要构建一个强类型 ListDataPointsRequest,指定目标用户和数据类型路径。然后,您在桩上调用 ListDataPoints RPC,并传递请求对象。gRPC 库会将消息序列化为二进制格式,通过 HTTP/2 传输,并返回强类型响应消息。
  • 访问数据和枚举映射(第 67-77 行):Protobuf 消息使用高效的类型。对于枚举值,您可以使用生成的描述符辅助函数(例如 DataSource.Platform.Name() 和 Exercise.ExerciseType.Name())将 API 返回的原始数值枚举值转换为人性化名称(例如 WALKING 或 FITBIT)。

7. 运行脚本并验证回答

执行客户端脚本并授权访问。

  1. 在终端中(仍处于活跃虚拟环境中,在根 health-grpc-codelab 目录中),运行以下命令:
    python3 client.py
    
  2. 该脚本将输出:
    Retrieving OAuth 2.0 credentials...
    Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/v2/auth...
    
    您的网络浏览器应该会自动打开权限请求页面。
  3. 使用在 Google Cloud 控制台项目中注册的测试用户电子邮件地址登录。
  4. 在权限请求页面上,点击继续以批准权限。
  5. 成功后,您会看到浏览器显示 The authentication flow has completed. You may close this window.
  6. 返回终端。该脚本将输出我们在移动应用中手动记录的锻炼数据:
    Making gRPC requests...
    Sending ListDataPoints RPC...
    --- Success ---
    Data Point ID: users/123456789/dataTypes/exercise/dataPoints/8896720705097069096
    Platform: FITBIT
    Exercise type: WALKING
    Display Name: Walk
    Start Time: 2026-02-23T13:10:00Z
    Calories (kcal): 16
    Steps: 2038
    ----------------
    

8. 提取其他数据类型

如需检索其他类型的数据(例如每日步数),您需要修改 Python 脚本中的请求路径。如果新数据类型需要不同的权限,您还必须更新 OAuth 范围。

请确保您在 health-grpc-codelab 目录的根目录下运行以下步骤和终端命令,并且您的 Python 虚拟环境仍处于活跃状态。

在 Google Cloud 控制台中更新范围

如果现有权限未涵盖新的数据类型,请执行以下操作:

  1. 在 Google Cloud 控制台中,依次前往 API 和服务 > OAuth 权限请求页面(或前往数据访问权限,查看 Google Health API 设置)。
  2. 添加与新数据类型对应的必需范围。
  3. 保存配置。

更新 client.py

按如下方式修改 client.py 中的配置和查询路径:

  1. 更新文件顶部的 SCOPES 列表,使其与 Google Cloud 控制台中添加的新权限范围保持一致。
  2. 在 fetch_health_data_grpc 函数中找到以下代码块:
    # 3. Request data points for data type "exercise"
    print("Sending ListDataPoints RPC...")
    request = data_points_pb2.ListDataPointsRequest(parent='users/me/dataTypes/exercise')
    response = stub.ListDataPoints(request)
    
  3. 将父级查询路径从 'users/me/dataTypes/exercise' 更改为 'users/me/dataTypes/steps'(或更改为其他数据类型路径)。
  4. 调整控制台输出格式,使其与新数据类型响应的结构相匹配。例如:
    # 3. Request data points for data type "steps"
    print("Sending ListDataPoints RPC for steps...")
    request = data_points_pb2.ListDataPointsRequest(parent='users/me/dataTypes/steps')
    response = stub.ListDataPoints(request)
    
    # 4. Display result
    print('--- Success ---')
    for dp in response.data_points:
        # Steps data structures contain interval and count values
        print(f"Start Time: {dp.steps.interval.start_time.ToJsonString()}")
        print(f"Count: {dp.steps.count}")
        print('----------------')
    

清除本地令牌缓存

OAuth 访问令牌会缓存在本地。如需强制身份验证流程请求新范围,请删除本地 token.json 文件:

rm token.json

重新运行脚本

执行更新后的客户端脚本,使用更新后的范围再次完成授权流程,并输出提取的数据:

python3 client.py

9. 恭喜

恭喜!

您已成功设置 Google Cloud 桌面客户端 ID、配置 Python 环境、检索并编译 Google Health API proto 架构,以及执行端到端经过身份验证的 gRPC 请求来提取健康与健身数据。

您可以根据需要自定义 client.py 脚本,以提取其他数据类型(例如 steps 或 sleep)、使用时间间隔过滤查询,或使用标准 gRPC 端点写入数据点。

更多信息: