用戶端程式庫

本頁面提供 Google Health API 的存取連結。

Google Health API 用戶端程式庫

Google Health API 是以 HTTP 和 JSON 做為建構基礎,因此所有標準 HTTP 用戶端都可以向 Google Health API 傳送要求並剖析回應。

不過,您可能想使用 Google API 用戶端程式庫,而非手動建立 HTTP 要求及剖析回應。用戶端程式庫提供更完善的語言整合和安全性,且支援發出需要使用者授權的呼叫。

Go

取得 適用於 Go 的 Google Health API 用戶端程式庫最新版本。閱讀用戶端程式庫的開發人員指南

Java

本頁說明如何透過適用於 Java 的 Google API 用戶端程式庫開始使用 Google Health API。詳情請參閱下列說明文件:

在專案中加入用戶端程式庫

從下列分頁選取您的建構環境 (Maven 或 Gradle):

Maven

請將以下內容新增到 pom.xml 檔案中:

您可以在這裡找到 Maven Central Repository 提供的所有版本。

Gradle

請將以下內容新增到 build.gradle 檔案中:

您可以在這裡找到 Maven Central Repository 提供的所有版本。

JavaScript

閱讀用戶端程式庫的開發人員指南

.NET

本頁說明如何透過適用於 .NET 的 Google API 用戶端程式庫開始使用 Google Health API。詳情請參閱以下說明文件:

下載程式庫

安裝 NuGet 套件:Google.Apis

Node.js

取得適用於 Node.js 的 Google Health API 用戶端程式庫最新版本。閱讀用戶端程式庫的開發人員指南

Obj-C

取得最新版適用於 Objective-C 的 Google Health API 用戶端程式庫。閱讀用戶端程式庫的開發人員指南

PHP

取得最新版適用於 PHP 的 Google Health API 用戶端程式庫。閱讀用戶端程式庫的開發人員指南

Python

本頁說明如何透過適用於 Python 的 Google API 用戶端程式庫 (第 1 版/第 2 版) 開始使用 Google Health API。詳情請參閱下列說明文件:

系統需求

安裝用戶端程式庫

您可以使用套件管理工具或是手動下載並安裝 Python 用戶端程式庫:

管理安裝作業

使用 pip 或 setuptools 管理安裝作業 (可能必須先執行 sudo):

  • pip (建議選項):
    pip install --upgrade google-api-python-client
  • Setuptools
    easy_install --upgrade google-api-python-client

手動安裝

  1. 下載最新版 Python 用戶端程式庫
  2. 解壓縮程式碼。
  3. 安裝:
    python setup.py install

App Engine

App Engine Python 執行階段環境並未安裝 Python 用戶端程式庫,因此您必須將這類程式庫複製到應用程式中,就像第三方用戶端程式庫一樣。

Ruby

本頁說明如何透過適用於 Ruby 的 Google API 用戶端程式庫開始使用 Google Health API。詳情請參閱下列說明文件:

安裝 google-api-client Gem

視您的系統而定,您可能必須在這些指令前加上 sudo

如果您從未安裝適用於 Ruby 的 Google API 用戶端程式庫,請使用 RubyGems 進行安裝:

gem install google-api-client

如果您已安裝 Gem,請更新至最新版本:

gem update -y google-api-client

開始使用 Ruby 專用的 Google API 用戶端程式庫

如要瞭解如何提出第一個要求,請參閱入門指南

gRPC

Google Health API 也支援 gRPC,可高效擷取資料。除了安裝用戶端程式庫,使用 gRPC 前,還需要取得 API 的通訊協定緩衝區定義,並產生用戶端 Stub 程式碼,才能提出要求。

  1. 安裝 gRPC 程式庫:
    • 使用 pip install grpcio grpcio-tools google-auth-oauthlib 安裝依附元件。
  2. 產生用戶端程式碼:
    • 取得 Google Health API .proto 定義 (例如 data_points.proto)。
    • 執行 python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. path/to/your/data_points.proto,生成存根程式碼。
  3. 實作 OAuth 2.0 並發出 gRPC 要求:
    • 使用 google-auth-oauthlib 進行授權,並使用產生的用戶端虛設常式發出 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 os
import json
import grpc

# Generated gRPC code from data_points.proto
# These imports depend on the output of grpc_tools
try:
    import data_points_pb2
    import data_points_pb2_grpc
except ImportError:
    print("Please generate gRPC code from data_points.proto")
    data_points_pb2 = None
    data_points_pb2_grpc = None

# --- REPLACE WITH YOUR VALUES ---
CLIENT_SECRETS_FILE = 'path/to/your/client_secret.json'
SCOPES = ['https://www.googleapis.com/auth/health']  # Add other scopes as needed
TOKEN_FILE = 'token.json'
GRPC_ENDPOINT = 'health.googleapis.com' # Google Health API gRPC endpoint

def get_credentials():
    """Gets or creates OAuth 2.0 credentials."""
    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_FILE):
        with open(TOKEN_FILE, 'r') as token:
            creds = Credentials.from_authorized_user_info(json.load(token), SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if creds and creds.expired and creds.refresh_token:
        try:
            creds.refresh(Request())
        except Exception as e:
            creds = None  # Force re-auth if refresh fails
    if not creds or not creds.valid:
        flow = InstalledAppFlow.from_client_secrets_file(
            CLIENT_SECRETS_FILE, SCOPES
        )
        creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        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."""
    if not data_points_pb2_grpc:
        return
    try:
        # Create an authenticated gRPC channel
        channel = secure_authorized_channel(creds, Request(), f'{GRPC_ENDPOINT}:443')
        # Create a stub for the DataPointsService
        stub = data_points_pb2_grpc.DataPointsServiceStub(channel)

        # Example: list steps data points for the authenticated user 'me'
        request = data_points_pb2.ListDataPointsRequest(parent='users/me/dataTypes/steps')
        response = stub.ListDataPoints(request)
        print('Health data via gRPC:', response)
    except grpc.RpcError as e:
        print(f'Error fetching data via gRPC: {e.code()} - {e.details()}')
    except Exception as e:
        print(f'An error occurred during gRPC call: {e}')

if __name__ == '__main__':
    try:
        creds = get_credentials()
        print("Fetching data using gRPC...")
        fetch_health_data_grpc(creds)
    except Exception as e:
        print(f"An error occurred: {e}")
  • 匯入程式庫:
    • grpc:gRPC Python 程式庫。
    • google.auth.transport.grpc:用於建立安全且經過驗證的管道。
    • data_points_pb2data_points_pb2_grpc:從 .proto 檔案產生的用戶端程式碼。
  • 設定:
    • CLIENT_SECRETS_FILEclient_secret.json 檔案的路徑。
    • SCOPES:必要權限。
    • TOKEN_FILE:儲存 OAuth 權杖的路徑。
    • GRPC_ENDPOINT:Google Health gRPC 服務的主機名稱。
  • get_credentials()
    • 從檔案載入用戶端密鑰、使用 InstalledAppFlow 中的 google-auth-oauthlib 管理授權、嘗試載入已儲存的憑證,或視需要啟動 OAuth 2.0 流程。
  • fetch_health_data_grpc()
    • 使用使用者的憑證建立經過驗證的安全 gRPC 管道。
    • 使用管道初始化 DataPointsServiceStub
    • 建立 ListDataPointsRequest,要求 users/me 的步數資料。
    • 呼叫 ListDataPoints RPC 方法並列印回應。
  • 錯誤處理:程式碼包含處理 gRPC 和其他錯誤的基本 try...except 區塊。