Get Google Fit API data in Python

Overview

You need to use OAuth2 to get data with the Google Fit API. It is convenient to use google-api-python-client when retrieving data using OAuth2. The method to get the data using google-api-python-client is described below.

Work procedure

  1. Install the Google Fit app on your smartphone
  2. Enable the Google Fit API in the Google API Console and download the json file. (File name is oauth2.json) --See below for articles that have been summarized in detail. -[I tried to get Google Fit data in C #! ](Https://qiita.com/tsumasakky/items/39853ee3680b1ce227e5#API activation)
  3. Install google-api-python-client with the following command pip3 install google-api-python-client
  4. Execute the following source
  5. Since there is no authentication information at the first startup, access the URL output by the browser and pass OAuth2 authentication

Execution source

getfit.py


import os
import json
import httplib2
import requests

import time
from datetime import datetime, timedelta
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow, flow_from_clientsecrets
from oauth2client.file import Storage

OAUTH_SCOPE = 'https://www.googleapis.com/auth/fitness.activity.read'
DATA_SOURCE = "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
CREDENTIALS_FILE = "./secret/credentials"

def auth_data():

    credentials = ""

    if os.path.exists(CREDENTIALS_FILE):
        credentials = Storage(CREDENTIALS_FILE).get()
    else:
        #flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
        flow = flow_from_clientsecrets(
            #Specify the JSON file for OAuth acquired when API is enabled
            './secret/oauth2.json',
            #Specify the scope
            scope=OAUTH_SCOPE,
            #Specify the token receiving method after user authentication (described later)
            redirect_uri=REDIRECT_URI)

        authorize_url = flow.step1_get_authorize_url()
        print('Please start the following URL in your browser.')
        print(authorize_url)

        code = input('Please enter Code: ').strip()
        credentials = flow.step2_exchange(code)

        if not os.path.exists(CREDENTIALS_FILE):
            Storage(CREDENTIALS_FILE).put(credentials)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

    fitness_service = build('fitness', 'v1', http=http)

    return fitness_service


def retrieve_data(fitness_service, dataset):

    return fitness_service.users().dataSources(). \
        datasets(). \
        get(userId='me', dataSourceId=DATA_SOURCE, datasetId=dataset). \
        execute()


def nanoseconds(nanotime):
    """
Convert to nanoseconds
    """
    dt = datetime.fromtimestamp(nanotime // 1000000000)
    return dt.strftime('%Y-%m-%d %H:%M:%S')


def logwrite(date, step):
    with open('./data/step.log', 'a') as outfile:
        outfile.write(str(date) + "," + str(step) + "\n")


if __name__ == "__main__":

    authdata = auth_data()

    #Get the data for the previous day
    TODAY = datetime.today() - timedelta(days=1)
    STARTDAY = datetime(TODAY.year, TODAY.month, TODAY.day, 0, 0, 0)
    NEXTDAY = datetime(TODAY.year, TODAY.month, TODAY.day, 23, 59, 59)
    NOW = datetime.today()

    START = int(time.mktime(STARTDAY.timetuple())*1000000000)
    NEXT = int(time.mktime(NEXTDAY.timetuple())*1000000000)
    END = int(time.mktime(NOW.timetuple())*1000000000)
    data_set = "%s-%s" % (START, NEXT)

    while True:

        if END < NEXT:
            break

        dataset = retrieve_data(authdata, data_set)

        starts = []
        ends = []
        values = []
        for point in dataset["point"]:
            if int(point["startTimeNanos"]) > START:
                starts.append(int(point["startTimeNanos"]))
                ends.append(int(point["endTimeNanos"]))
                values.append(point['value'][0]['intVal'])

        print("From: {}".format(nanoseconds(min(starts))))
        print("To: {}".format(nanoseconds(max(ends))))
        print("Steps:{}".format(sum(values)))

        step = sum(values)

        startdate = STARTDAY.date()
        logwrite(startdate, step)

        STARTDAY = STARTDAY + timedelta(days=1)
        NEXTDAY = NEXTDAY + timedelta(days=1)
        START = int(time.mktime(STARTDAY.timetuple())*1000000000)
        NEXT = int(time.mktime(NEXTDAY.timetuple())*1000000000)
        data_set = "%s-%s" % (START, NEXT)

        time.sleep(5)

Reference page

-I tried to get Google Fit data in C #! -[Python] How to do Google API OAuth in embedded application

Recommended Posts

Get Google Fit API data in Python
Get Youtube data in Python using Youtube Data API
Get LEAD data using Marketo's REST API in Python
[Python] Get insight data using Google My Business API
Get data from Quandl in Python
Get data from analytics API with Google API Client for python
Get additional data in LDAP with python
Creating Google Spreadsheet using Python / Google Data API
Evernote API in Python
Get date in Python
C API in Python 3
Get time series data from k-db.com in Python
[Python] Get all comments using Youtube Data API
Run Google Analytics API (core v3) in python
Get image URL using Flickr API in Python
Get stock price data with Quandl API [Python]
Copy data between Google Keep accounts in Python
What to do to get google spreadsheet in python
Hit Mastodon's API in Python
Get YouTube Comments in Python
Handle Ambient data in Python
Get last month in python
Display UTM-30LX data in Python
Get Youtube data with python
Get data from GPS module at 10Hz in Python
Get Terminal size in Python
Explicitly get EOF in python
Get data via salesforce API (Bulk API) in Python and load it into BigQuery
Blender Python API in Houdini (Python 3)
Get Evernote notes in Python
Google Drive Api Tips (Python)
Get Japanese synonyms in Python
Get your heart rate from the fitbit API in Python!
Inflating text data by retranslation using google translate in Python
Hit REST in Python to get data from New Relic
Issue reverse geocoding in Japanese with Python Google Maps API
Play with YouTube Data API v3 using Google API Python Client
Call github api in python to get pull request information
Get Salesforce data using REST API
Getting the arXiv API in Python
Data acquisition using python googlemap api
Get reviews with python googlemap api
Hit the Sesami API in Python
[Python3] Google translate google translate without using api
Handle NetCDF format data in Python
[Python] Get economic data with DataReader
Download Google Drive files in Python
Create Gmail in Python without API
Get Amazon data using Keep API # 1 Get data
Hashing data in R and Python
Get, post communication memo in Python
Hit the web API in Python
Get upcoming weather from python weather api
Get the desktop path in Python
Quickly implement REST API in Python
Get the host name in Python
Access the Twitter API in Python
Get started with Python in Blender
Use Google Analytics API from Python
Hit the New Relic API in Python to get the server status
Regularly upload files to Google Drive using the Google Drive API in Python