Skip to main content

An asynchronous, type-safe Python client library for the Google Health API.

Project description

Python Google Health API Client Library

An asynchronous, type-safe Python client library for the Google Health API (health.googleapis.com/v4). This library is designed to help developers migrate from the legacy Fitbit Web API to the Google Health API.

It exposes Google Health data types as clean, type-annotated properties on the client (e.g., api.steps and api.heart_rate).

Features

  • Asynchronous: Built on aiohttp for non-blocking asynchronous requests.
  • Type-safe: Leverages Python dataclasses and mashumaro for seamless JSON serialization and deserialization, matching the exact Google Health API schemas.
  • AIP-160 Filter Support: Built-in helper to automatically translate timestamp queries into Google API filter expressions.
  • Auto-pagination: Paginated results wrap list endpoints and provide asynchronous iterators to traverse pages easily.

Supported Data Types

Currently supported data types:

  • Steps (api.steps)
  • Heart Rate (api.heart_rate)
  • Sleep (api.sleep)
  • Distance (api.distance)
  • Basal Energy Burned (api.basal_energy_burned)
  • Active Energy Burned (api.active_energy_burned)
  • Total Calories (api.total_calories)
  • VO2 Max (api.vo2_max)
  • Weight (api.weight)
  • Floors (api.floors)
  • Hydration Log (Water) (api.hydration_log)
  • Nutrition Log (Food) (api.nutrition_log)
  • Daily Resting Heart Rate (api.daily_resting_heart_rate)

Installation

Install the package from PyPI using uv:

uv pip install google-health-api

Quickstart

import asyncio
import aiohttp
from google_health_api.api import GoogleHealthApi
from google_health_api.auth import AbstractAuth

class SimpleAuth(AbstractAuth):
    def __init__(self, websession: aiohttp.ClientSession, access_token: str) -> None:
        super().__init__(websession)
        self._access_token = access_token

    async def async_get_access_token(self) -> str:
        return self._access_token

async def main():
    async with aiohttp.ClientSession() as session:
        # Initialize authorization wrapper with your Google OAuth 2.0 access token
        auth = SimpleAuth(session, "YOUR_ACCESS_TOKEN")
        api = GoogleHealthApi(auth)

        # 1. Fetch steps from the last 24 hours
        from datetime import datetime, timezone, timedelta
        end_time = datetime.now(timezone.utc)
        start_time = end_time - timedelta(days=1)

        result = await api.steps.list(start_time=start_time, end_time=end_time)
        print("Steps:")
        for point in result.data_points:
            print(f"  Count: {point.data.count} steps")
            print(f"  Time: {point.data.start_time} to {point.data.end_time}")

        # 2. Fetch heart rate records
        hr_result = await api.heart_rate.list(start_time=start_time, end_time=end_time)
        print("Heart Rates:")
        for point in hr_result.data_points:
            print(f"  BPM: {point.data.bpm}")

if __name__ == "__main__":
    asyncio.run(main())

Development and Testing

Verify code quality and type safety:

./script/lint

Run mock tests:

./script/test

Verify with a live account using the browser-based OAuth 2.0 Installed App Flow:

  1. Create an OAuth client ID for a "Desktop application" in the Google Cloud Console.
  2. Download the JSON key file, rename it to client_secret.json, and place it in the project root.
  3. Authenticate and query via the command-line interface tool:
    # Log in via your web browser (stores credentials in token.json)
    google-health-cli login
    
    # List step data points
    google-health-cli steps list --days 7 --limit 5
    
    # List heart rate data points
    google-health-cli heart-rate list --days 7 --limit 5
    
    # Retrieve user profile details
    google-health-cli profile get
    

Command-Line Interface (CLI)

The package installs a real binary executable google-health-cli designed with Agent DX (AI Agent Developer Experience) and Human DX principles.

Key Capabilities

  • Dynamic Schema Introspection: Let agents query request/response layouts at runtime.
    google-health-cli schema
    google-health-cli schema steps.list
    
  • Raw JSON Payloads: Pass structured queries or write payloads directly to bypass flat CLI argument limits.
    # Query filtering via --params
    google-health-cli --params '{"pageSize": 5, "startTime": "2026-06-26T00:00:00Z"}' steps list
    
    # Mutation via --json
    google-health-cli --json '{"steps": {"count": 100, ...}}' steps create
    
  • Context Token Discipline: Use fields/masking filters to prevent bloating agent reasoning limits.
    google-health-cli --fields "dataPoints(steps(count,interval))" steps list
    
  • Safety Rails & Dry-Runs: Validate mutating requests locally before hitting the API.
    google-health-cli --dry-run --json '{"steps": {"count": 100, ...}}' steps create
    
  • Headless Integration: Autodetects environment variables for credentials in headless agent contexts.
    export GOOGLE_HEALTH_CLI_TOKEN="YOUR_OAUTH_TOKEN"
    google-health-cli profile get
    

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

google_health_api-0.5.0.tar.gz (54.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

google_health_api-0.5.0-py3-none-any.whl (47.0 kB view details)

Uploaded Python 3

File details

Details for the file google_health_api-0.5.0.tar.gz.

File metadata

  • Download URL: google_health_api-0.5.0.tar.gz
  • Upload date:
  • Size: 54.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for google_health_api-0.5.0.tar.gz
Algorithm Hash digest
SHA256 9c1ece287f028e1434547e838ffa5b74c70c74997334837ccfe5cc64c6ec919d
MD5 6c8e3465c952cb4807d85217074cd638
BLAKE2b-256 12ccf807daa0ee9a3af2b4daf8ef1ca4daa1216154257404e85b3df362b4aee9

See more details on using hashes here.

Provenance

The following attestation bundles were made for google_health_api-0.5.0.tar.gz:

Publisher: publish.yaml on allenporter/python-google-health-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file google_health_api-0.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for google_health_api-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1ea23de7709c66983eae9261070e187546a530e0438c4b3c82479c86d2cd0d71
MD5 73c29e90414b196f17d0964c8eacf48b
BLAKE2b-256 a4b2c20d90ed98a24ab0f4aba197d95f88399551273aa665248c36096b8976f0

See more details on using hashes here.

Provenance

The following attestation bundles were made for google_health_api-0.5.0-py3-none-any.whl:

Publisher: publish.yaml on allenporter/python-google-health-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page