클라이언트 라이브러리

이 페이지에서는 Google Health API에 액세스하는 편리한 방법을 제공합니다.

Google Health API 클라이언트 라이브러리

Google Health API는 HTTP 및 JSON을 기반으로 만들어졌으므로 모든 표준 HTTP 클라이언트에서 Indexing API로 요청을 전송하고 응답을 파싱할 수 있습니다.

그러나 수동으로 HTTP 요청을 만들고 응답을 파싱하는 대신 Google API 클라이언트 라이브러리를 사용할 수도 있습니다. 클라이언트 라이브러리는 우수한 언어 통합, 향상된 보안, 사용자 승인이 필요한 호출에 대한 지원을 제공합니다.

Go

최신 Go용 Google Health API 클라이언트 라이브러리를 다운로드하세요. 클라이언트 라이브러리의 개발자 가이드를 읽어 보시기 바랍니다.

자바

이 페이지에는 자바용 Google API 클라이언트 라이브러리를 사용하여 Google Health API를 시작하는 데 필요한 정보가 포함되어 있습니다. 자세한 내용은 다음 설명서를 참고하세요.

프로젝트에 클라이언트 라이브러리 추가하기

다음 탭에서 빌드 환경(Maven 또는 Gradle)을 선택합니다.

자바스크립트

클라이언트 라이브러리의 개발자 가이드를 읽어 보세요.

.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 클라이언트 라이브러리 (v1/v2)를 사용하여 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

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의 프로토콜 버퍼 정의를 가져오고 클라이언트 측 스텁 코드를 생성해야 합니다.

  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_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-oauthlibInstalledAppFlow를 사용하여 승인을 관리하고, 저장된 사용자 인증 정보를 로드하거나 필요한 경우 OAuth 2.0 플로우를 시작합니다.
  • fetch_health_data_grpc():
    • 사용자의 사용자 인증 정보를 사용하여 보안 인증 gRPC 채널을 만듭니다.
    • 채널로 DataPointsServiceStub을 초기화합니다.
    • users/me의 단계 데이터를 요청하는 ListDataPointsRequest를 만듭니다.
    • ListDataPoints RPC 메서드를 호출하고 응답을 출력합니다.
  • 오류 처리: 코드에는 gRPC 및 기타 오류를 처리하기 위한 기본 try...except 블록이 포함되어 있습니다.