Client libraries

This page provides links to convenient ways to access the Google Health API.

Google Health API client libraries

The Google Health API is built on HTTP and JSON, so any standard HTTP client can send requests to it and parse the responses.

However, instead of creating HTTP requests and parsing responses manually, you may want to use the Google APIs client libraries. The client libraries provide better language integration, improved security, and support for making calls that require user authorization.

Go

Get the latest Google Health API client library for Go. Read the client library's developer's guide.

Java

This page contains information about getting started with the Google Health API by using the Google API Client Library for Java. For more information, see the following documentation:

Add the client library to your project

Select your build environment (Maven or Gradle) from the following tabs:

JavaScript

Read the client library's developer's guide.

.NET

This page contains information about getting started with the Google Health API by using the Google API Client Library for .NET. For more information, see the following documentation:

Downloading the library

Install the NuGet package: Google.Apis.

Node.js

Get the latest Google Health API client library for Node.js. Read the client library's developer's guide.

Obj-C

Get the latest Google Health API client library for Objective-C. Read the client library's developer's guide.

PHP

Get the latest Google Health API client library for PHP. Read the client library's developer's guide.

Python

This page contains information about getting started with the Google Health API by using the Google API Client Library for Python (v1/v2). For more information, see the following documentation:

System requirements

Install the client library

You can either use a package manager or manually download and install the Python client library:

Managed install

Use pip or setuptools to manage your installation. You might need to run sudo first.

  • pip (preferred):
    pip install --upgrade google-api-python-client
  • Setuptools:
    easy_install --upgrade google-api-python-client

Manual install

  1. Download the latest client library for Python.
  2. Unpack the code.
  3. Install:
    python setup.py install

App Engine

Because the Python client libraries aren't installed in the App Engine Python runtime environment, you must copy them into your application just like third-party libraries.

Ruby

This page contains information about getting started with the Google Health API by using the Google API Client Library for Ruby. For more information, see the following documentation:

Install the google-api-client gem

Depending on your system, you might need to prepend these commands with sudo.

If you haven't installed the Google API Client Library for Ruby before, install by using RubyGems:

gem install google-api-client

If you already have the gem installed, update to the latest version:

gem update -y google-api-client

Get started with the Google API Client Library for Ruby

To learn how to make your first request, see the Get started guide.

gRPC

The Google Health API also supports gRPC for high-performance data retrieval. In addition to installing client libraries, using gRPC requires obtaining the API's Protocol Buffers definitions and generating client-side stub code before making requests.

  1. Install gRPC libraries:
    • Use pip install grpcio grpcio-tools google-auth-oauthlib to install dependencies.
  2. Generate client code:
    • Obtain the Google Health API .proto definitions (for example, data_points.proto).
    • Run python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. path/to/your/data_points.proto to generate stub code.
  3. Implement OAuth 2.0 and make gRPC requests:
    • Use google-auth-oauthlib for authorization and the generated client stub to make gRPC requests, as shown in the following example.
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}")
  • Import Libraries:
    • grpc: The gRPC Python library.
    • google.auth.transport.grpc: For creating secure, authenticated channels.
    • data_points_pb2, data_points_pb2_grpc: Client code generated from .proto files.
  • Configuration:
    • CLIENT_SECRETS_FILE: Path to your client_secret.json file.
    • SCOPES: The required permissions.
    • TOKEN_FILE: Path to store OAuth tokens.
    • GRPC_ENDPOINT: The hostname for the Google Health gRPC service.
  • get_credentials():
    • Loads client secrets from file, uses InstalledAppFlow from google-auth-oauthlib to manage authorization, attempts to load stored credentials, or initiates the OAuth 2.0 flow if needed.
  • fetch_health_data_grpc():
    • Creates a secure, authenticated gRPC channel using the user's credentials.
    • Initializes a DataPointsServiceStub with the channel.
    • Creates a ListDataPointsRequest to request steps data for users/me.
    • Calls the ListDataPoints RPC method and prints the response.
  • Error Handling: The code includes basic try...except blocks for handling gRPC and other errors.