Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get total step count from Google Fit API for current day
#! /usr/bin/env python
#-*- coding: utf-8 -*-
import json
import httplib2
import time
from datetime import datetime
from datetime import timedelta
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
# Copy your credentials from the Google Developers Console
CLIENT_ID = 'XXXXXXXXXXXXXXXXXX.apps.googleusercontent.com'
CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX'
# Check https://developers.google.com/fit/rest/v1/reference/users/dataSources/datasets/get
# for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/fitness.activity.read'
# DATA SOURCE
DATA_SOURCE = "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
# The ID is formatted like: "startTime-endTime" where startTime and endTime are
# 64 bit integers (epoch time with nanoseconds).
TODAY = datetime.today().date()
NOW = datetime.today()
START = int(time.mktime(TODAY.timetuple())*1000000000)
END = int(time.mktime(NOW.timetuple())*1000000000)
DATA_SET = "%s-%s" % (START, END)
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
def retrieve_data():
"""
Run through the OAuth flow and retrieve credentials.
Returns a dataset (Users.dataSources.datasets):
https://developers.google.com/fit/rest/v1/reference/users/dataSources/datasets
"""
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser:'
print authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# 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.users().dataSources(). \
datasets(). \
get(userId='me', dataSourceId=DATA_SOURCE, datasetId=DATA_SET). \
execute()
def nanoseconds(nanotime):
"""
Convert epoch time with nanoseconds to human-readable.
"""
dt = datetime.fromtimestamp(nanotime // 1000000000)
return dt.strftime('%Y-%m-%d %H:%M:%S')
if __name__ == "__main__":
# Point of entry in execution mode:
dataset = retrieve_data()
with open('dataset.txt', 'w') as outfile:
json.dump(dataset, outfile)
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: ", nanoseconds(min(starts))
print "To: ", nanoseconds(max(ends))
print "Steps: %d" % sum(values)
@marksev1
Copy link

marksev1 commented Jun 19, 2017

This is nice, but this "Google Developers Console" is not free right? (or it is just for 12 months), is there any other option?

Is this console the "cloud console" or the "play developers console"?

@dkomando
Copy link

dkomando commented Jun 20, 2017

I believe the script is referencing referencing: https://developers.google.com/fit/

@marksev1
Copy link

marksev1 commented Jun 20, 2017

@marksev1
Copy link

marksev1 commented Jun 21, 2017

Edit: so now when i copy the verification code i get the following error:

Traceback (most recent call last):
File "getfit.py", line 68, in
dataset = retrieve_data()
File "getfit.py", line 46, in retrieve_data
credentials = flow.step2_exchange(code)
File "/home/msev/.virtualenvs/coding/local/lib/python2.7/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/msev/.virtualenvs/coding/local/lib/python2.7/site-packages/oauth2client/client.py", line 2089, in step2_exchange
raise FlowExchangeError(error_msg)
oauth2client.client.FlowExchangeError: invalid_clientUnauthorized

@YOONJIYEONG
Copy link

YOONJIYEONG commented May 28, 2019

what code should I put in code = raw_input('Enter verification code: ').strip()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment