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 移动应用,请按以下步骤操作:
- 在 Apple App Store 或 Google Play 商店中,搜索 Google Health 移动应用并下载。
- 选择应用图标。
- 点击使用 Google 账号登录
- 选择您的 Google 账号,然后按继续按钮。
2. 设置 Google Cloud 项目
您将使用 Google Cloud 控制台创建客户端 ID,并启用 Google Health API。
- 登录 Google Cloud 控制台。
- 如需创建新项目,请执行以下操作:
- 在项目选择器中点击选择项目。
- 在右上角,选择新建项目。
- 输入项目名称。
- 输入您的位置(例如“无组织”)。
- 点击创建按钮。
- 选择您的项目。
启用 Google Health API
- 点击左上角的菜单图标:

- 选择 API 和服务 > 库。
- 搜索“Google Health API”并启用。
设置 OAuth 凭证
如果您不在 Google Cloud 控制台中,请前往 Google Cloud 控制台。
- 点击左上角的菜单图标:

- 依次选择 API 和服务 > 凭证。
- 在顶部中心位置,依次选择 + 创建凭据 > OAuth 客户端 ID。
- 点击配置权限请求页面按钮。如果显示“尚未配置 Google Auth Platform”消息,请点击开始使用按钮。
- 在第 1 部分中:
- 输入应用名称。
- 输入用户支持邮箱。
- 点击下一步按钮。
- 在第 2 部分中:
- 选择外部。
- 点击下一步按钮。
- 在第 3 部分中:
- 在联系信息字段中输入您的邮箱。
- 点击下一步按钮。
- 在第 4 部分中:
- 点击复选框,同意 Google 的 API 服务用户数据政策。
- 点击创建按钮。
- 返回 API 和服务 > 凭据,然后依次选择 + 创建凭据 > OAuth 客户端 ID。
- 选择应用类型桌面应用。
- 输入客户端 ID 名称(例如“Google Health API gRPC Codelab”)。
- 点击创建按钮。
- Google 控制台会显示一条消息,告知您客户端 ID 已创建。点击下载 JSON 链接,下载客户端 ID 和客户端密钥文件。由于浏览器会使用包含您的客户端 ID 的默认名称(例如
client_secret_)下载该文件,因此您必须将该文件重命名为.json client_secret.json。稍后,我们会将此文件放入代码库中。 - 点击确定。您将返回到“OAuth 2.0 客户端 ID”页面。
添加测试用户
- 在左侧窗格中,选择受众群体。您应该会看到发布状态设置为测试,用户类型设置为外部。
- 在测试用户部分下,点击 + 添加用户按钮。输入您在 Google Health 移动应用中登录的 Google 账号的邮箱。
- 点击保存按钮。
向客户端 ID 添加范围
- 在左侧窗格中,选择数据访问。
- 点击添加或移除范围按钮。
- 在“API”列中,搜索“Google Health API”。在此 Codelab 中,我们将使用
https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly范围 - 选择范围后,按更新按钮返回“数据访问”页面。
- 点击保存按钮。
您已完成客户端 ID 的设置。
3. 向 Google Health 移动应用添加数据
对于 Google Health API 的新用户,您的 Google Health 账号中可能没有可供查询的数据。我们将手动添加一条锻炼日志,以便通过其中一个端点进行查询。如要手动记录锻炼,请按以下步骤操作:
- 在设备上打开 Google Health 移动应用。根据需要登录 Google Health 账号。
- 点按屏幕右下角的 + 按钮。
- 在手动记录部分,点按活动。
- 搜索锻炼类型步行并选择。
- 输入今天的开始时间。
- 将时长更改为 15 分钟。
- 将距离保留为 1.0 英里。
- 点按添加。
- 长按屏幕并向下滑动,将移动应用同步到 Google Health 服务器。松开手指后,您应该会看到移动应用开始同步。
- 在活动部分,你应该会看到手动记录的步行条目。

4. 设置 Python 项目和依赖项
我们将设置一个本地工作区目录,并建立一个 Python 虚拟环境来管理此 Codelab 的依赖项。
- 打开终端。
- 运行适用于您的操作系统的设置命令:
- 在 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)的软件包。
- 在 macOS/Linux 上:
- 将您在上一部分中下载并重命名的
client_secret.json凭证文件移至此父级health-grpc-codelab文件夹中。
5. 获取 proto 并生成桩
在通过 gRPC 请求数据之前,我们必须将与 Google Health API 匹配的协议缓冲区 (.proto) 定义编译为客户端桩。
由于架构依赖于各种共享的 Google API 文件(例如注解、操作和字段行为),因此最简单的方法是克隆官方的公开 Google API 代码库。
- 克隆
googleapisGitHub 代码库,编译所需的客户端架构,然后一步返回到父级工作区文件夹: 这将编译 protobuf 并直接在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 ..googleapis/google/devicesandservices/health/v4/子目录中生成.py桩文件。
6. 使用 Python 实现 gRPC 客户端代码
为了进行身份验证和请求数据,我们将编写一个脚本。
- 在
health-grpc-codelab目录的根目录下创建一个名为client.py的文件。 - 使用以下代码填充
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 行):
在 gRPC 中,通道表示与远程端点的连接。此代码使用channel = secure_authorized_channel(creds, Request(), f'{GRPC_ENDPOINT}:443')google-auth库中的secure_authorized_channel在端口 443 上建立安全的 TLS 连接,该连接会自动将 OAuth 2.0 授权凭据附加到所有调用元数据。 - 实例化客户端桩(第 58 行):
这会实例化一个本地客户端桩(或客户端类),用于表示 Health API 的stub = data_points_pb2_grpc.DataPointsServiceStub(channel)DataPointsService服务定义。您可以通过此桩直接调用所有远程过程。 - 执行 RPC 调用(第 62-63 行):
您需要构建一个强类型request = data_points_pb2.ListDataPointsRequest(parent='users/me/dataTypes/exercise') response = stub.ListDataPoints(request)ListDataPointsRequest,指定目标用户和数据类型路径。然后,您在桩上调用ListDataPointsRPC,并传递请求对象。gRPC 库会将消息序列化为二进制格式,通过 HTTP/2 传输,并返回强类型响应消息。 - 访问数据和枚举映射(第 67-77 行):Protobuf 消息使用高效的类型。对于枚举值,您可以使用生成的描述符辅助函数(例如
DataSource.Platform.Name()和Exercise.ExerciseType.Name())将 API 返回的原始数值枚举值转换为人性化名称(例如WALKING或FITBIT)。
7. 运行脚本并验证回答
执行客户端脚本并授权访问。
- 在终端中(仍处于活跃虚拟环境中,在根
health-grpc-codelab目录中),运行以下命令:python3 client.py - 该脚本将输出:
您的网络浏览器应该会自动打开权限请求页面。Retrieving OAuth 2.0 credentials... Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/v2/auth... - 使用在 Google Cloud 控制台项目中注册的测试用户电子邮件地址登录。
- 在权限请求页面上,点击继续以批准权限。
- 成功后,您会看到浏览器显示
The authentication flow has completed. You may close this window. - 返回终端。该脚本将输出我们在移动应用中手动记录的锻炼数据:
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 控制台中更新范围
如果现有权限未涵盖新的数据类型,请执行以下操作:
- 在 Google Cloud 控制台中,依次前往 API 和服务 > OAuth 权限请求页面(或前往数据访问权限,查看 Google Health API 设置)。
- 添加与新数据类型对应的必需范围。
- 保存配置。
更新 client.py
按如下方式修改 client.py 中的配置和查询路径:
- 更新文件顶部的
SCOPES列表,使其与 Google Cloud 控制台中添加的新权限范围保持一致。 - 在
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) - 将父级查询路径从
'users/me/dataTypes/exercise'更改为'users/me/dataTypes/steps'(或更改为其他数据类型路径)。 - 调整控制台输出格式,使其与新数据类型响应的结构相匹配。例如:
# 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 端点写入数据点。
更多信息:
- 在 RPC 参考指南中查看其他服务桩。
- 如需详细了解 OAuth 范围和访问令牌,请参阅设置 Google Cloud 和 OAuth 指南。