Skip to content

Instantly share code, notes, and snippets.

@cedricbonhomme
Created November 16, 2014 00:11
Show Gist options
  • Save cedricbonhomme/a8c96f1aeb41393dadf6 to your computer and use it in GitHub Desktop.
Save cedricbonhomme/a8c96f1aeb41393dadf6 to your computer and use it in GitHub Desktop.
Get your Google Fit data
#! /usr/bin/env python
#-*- coding: utf-8 -*-
import json
import httplib2
from datetime import datetime
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).
DATA_SET = "1051700038292387000-1451700038292387000"
# 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)
last_point = dataset["point"][-1]
print "Start time:", nanoseconds(int(last_point.get("startTimeNanos", 0)))
print "End time:", nanoseconds(int(last_point.get("endTimeNanos", 0)))
print "Data type:", last_point.get("dataTypeName", None)
print "Steps:", last_point["value"][0].get("intVal", None)
@tejovanthn
Copy link

Hey, I get Error: redirect_uri_mismatch error when I open the link the script puts out. How do I get around that?

@clairethebear
Copy link

Im sure its probably too late to help tejovanthn - but for anyone else stuck on this very helpful example of Google Fit authentication. You need to change the REDIRECT_URI to be the domain that you expect your application to redirect to. For example: yourappname.appspot.com.

Then go to the cloud developer console and navigate to the credentials, add OAuth 2.0 client ID -> enter the url that your application will be using including oauth2callback. For example:
yourappname.appspot.com
yourappname.appspot.com/
yourappname.appspot.com/oauth2callback
yourappname.appspot.com/oauth2callback/

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