このページでは、Google Health API にアクセスする便利な方法へのリンクを紹介します。
Google Health API クライアント ライブラリ
Google Health API は HTTP と JSON を使用して設計されているため、標準の HTTP クライアントであれば Google Health API にリクエストを送信しレスポンスを解析できます。
ただし、手動で HTTP リクエストを作成してレスポンスを解析するのではなく、Google API クライアント ライブラリを使用することをおすすめします。クライアント ライブラリでは、言語の統合性が高く、セキュリティも強化されています。また、ユーザーの承認が必要な呼び出しもサポートしています。
Go
Go 用の最新の Google Health API クライアント ライブラリを取得し、 クライアント ライブラリの デベロッパー ガイドをお読みください。
Java
このページには、Java 用 Google API クライアント ライブラリを使用して Google Health API にアクセスする方法が記載されています。 詳しくは以下のドキュメントをご覧ください。
- Google Health API の JavaDoc リファレンス
- Java 用 Google API クライアント ライブラリのデベロッパー ガイドを読む。
クライアント ライブラリをプロジェクトに追加する
以下のタブからビルド環境(Maven または Gradle)を選択します。
次のコードを pom.xml ファイルに追加します。
次のコードを build.gradle ファイルに追加します。
JavaScript
クライアント ライブラリのデベロッパー ガイドをご覧ください。
.NET
このページには、.NET 用 Google API クライアント ライブラリを使用して Google Health API にアクセスする方法が記載されています。詳しくは以下のドキュメントをご覧ください。
- Google Health API の .NET リファレンス ドキュメント
- .NET 用 Google 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 クライアント ライブラリ(v1/v2)を使用して Google Health API にアクセスする方法が記載されています。 詳しくは以下のドキュメントをご覧ください。
- Google Health API の PyDoc リファレンス
- Python 用 Google API クライアント ライブラリ(v1/v2)のデベロッパー ガイド
システム要件
- オペレーティング システム:
- Linux
- macOS X
- Windows
- v1 クライアント ライブラリでは Python 2.7 以上が必要です。v2 クライアント ライブラリには 3.7 以上が必要です。
クライアント ライブラリをインストールする
パッケージ マネージャーを使用するか、Python クライアント ライブラリを手動でダウンロードしてインストールできます。
マネージド インストール
pip または setuptools を使用してインストールを管理します。最初に を実行しなければならない場合があります。最初に
sudoを実行しなければならない場合があります。
- pip(推奨):
pip install --upgrade google-api-python-client
- setuptools:
easy_install --upgrade google-api-python-client
手動インストール
- 最新の Python 用クライアント ライブラリをダウンロードします。
- コードを解凍します。
- 以下をインストールします。
python setup.py install
App Engine
Python クライアント ライブラリは App Engine 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 の Protocol Buffers 定義を取得し、クライアントサイドのスタブコードを生成する必要があります。
- gRPC ライブラリをインストールします。
pip install grpcio grpcio-tools google-auth-oauthlibを使用して依存関係をインストールします。
- クライアント コードを生成します。
- Google Health API
.proto定義(たとえば、data_points.proto)を取得します。 python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. path/to/your/data_points.protoを実行して スタブコードを生成します。
- Google Health API
- 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_pb2、data_points_pb2_grpc:.protoファイルから生成されたクライアント コード。
- 構成:
CLIENT_SECRETS_FILE:client_secret.jsonファイルのパス。SCOPES: 必要な権限。TOKEN_FILE: OAuth トークンを保存するパス。GRPC_ENDPOINT: Google Health gRPC サービスのホスト名。
get_credentials():- ファイルからクライアント シークレットを読み込み、
google-auth-oauthlibのInstalledAppFlowを使用して承認を管理し、保存された認証情報の読み込みを試行します。必要に応じて OAuth 2.0 フローを開始します。
- ファイルからクライアント シークレットを読み込み、
fetch_health_data_grpc():- ユーザーの認証情報を使用して、安全な認証済み gRPC チャネルを作成します。
- チャネルを使用して
DataPointsServiceStubを初期化します。 users/meのステップデータをリクエストするListDataPointsRequestを作成します。ListDataPointsRPC メソッドを呼び出してレスポンスを出力します。
- エラー処理: このコードには、gRPC エラーやその他のエラーを処理するための基本的な
try...exceptブロックが含まれています。