Fetch sleep data from google fitness api by service account

53 Views Asked by At

I want to retrieve sleep data using the Google Fitness API through a service account, and I have already configured OAuth 2.0 and the service account. However, I am still unable to access the sleep data, even though I am certain there is data available during this time period.

from flask import Flask, jsonify
import requests
from google.oauth2 import service_account
from google.auth.transport.requests import Request

app = Flask(__name__)

# Load Service Account credentials
SERVICE_ACCOUNT_FILE = "gfit-credentials.json"  # Replace with the path to your JSON key file
SCOPES = ['https://www.googleapis.com/auth/fitness.sleep.read']  # Adjust scopes as needed

credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

START_TIME_MILLIS = 1680696000000
END_TIME_MILLIS = 1688472000000
SLEEP_STAGE_MAP = {
    1: 'Awake (during sleep cycle)',
    2: 'Sleep',
    3: 'Out-of-bed',
    4: 'Light sleep',
    5: 'Deep sleep',
    6: 'REM',
}

@app.route('/sleep_data', methods=['GET'])
def get_sleep_data():
    try:

        if credentials.valid is False:
            credentials.refresh(Request())
        
        access_token = credentials.token

        print(f"Access Token: {access_token}")

        if access_token is None:
            return "Access token is not available", 400

        headers = {'Authorization': 'Bearer ' + access_token}
        data = {
            'aggregateBy': [{'dataTypeName': 'com.google.sleep.segment'}],
            'startTimeMillis': START_TIME_MILLIS,
            'endTimeMillis': END_TIME_MILLIS
        }
        api_response = requests.post(
            'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
            headers=headers, json=data
        )

        print(f"API Response: {api_response.status_code}, {api_response.text}")

        if api_response.status_code != 200:
            return f"Failed to fetch data: {api_response.text}", 400

        response_json = api_response.json()
        sleep_data = response_json.get('bucket', [])[0].get('dataset', [])[0].get('point', [])

        sleep_data_processed = [
            {**item, 'sleepStage': SLEEP_STAGE_MAP.get(item['value'][0]['intVal'], 'Unknown')}
            for item in sleep_data
        ]

        return jsonify(sleep_data_processed)

    except Exception as e:
        print('Error fetching data:', e)
        return "Error fetching data", 500


if __name__ == '__main__':
    app.run(port=1234)

After running the Flask application and accessing http://localhost:1234/sleep_data, this is the result I obtained for retrieving the data.

API Response: 200, {
  "bucket": [
    {
      "startTimeMillis": "1680696000000",
      "endTimeMillis": "1688472000000",
      "dataset": [
        {
          "dataSourceId": "derived:com.google.sleep.segment:com.google.android.gms:merged",
          "point": []
        }
      ]
    }
  ]
}
0

There are 0 best solutions below