For this initial step, we are using python-fitbit, a Python client accessing the Fitbit API. We furthermore require an exisiting Fitbit OAuth 2.0 Client (Consumer) ID and Client (Consumer) Secret. These can be obtained by registering an app here.
Let's make sure that all Python dependencies needed below can be loaded:
import fitbit # clone https://github.com/orcasgit/python-fitbit
from bin.parse_credentials import parse_client_credentials, parse_tokens # clone https://github.com/JungeAlexander/fitbit-data
Afterwards, save the Client ID and Client Secret to a text file named client_id_secret.txt
located in the same directory as this Jupyter notebook. client_id_secret.txt
should look like this:
id = 123ABC
secret = 1234567890abcdef1234567890abcdef123456789
Load the credentials into two variables using a function shipped with this repository:
client_id, client_secret = parse_client_credentials('client_id_secret.txt')
Furthermore, API access and refresh tokens are required for python-fitbit to access Fitbit data. These can be obtained using the script gather_keys_oauth2.py
shipped with python-fitbit.
Execute the following command to write the output of gather_keys_oauth2.py
to access_refresh_tokens.txt
:
!./gather_keys_oauth2.py $client_id $client_secret >access_refresh_tokens.txt 2>/dev/null
Now load access and refresh tokens into two variables:
access_token, refresh_token = parse_tokens('access_refresh_tokens.txt')
authd_client = fitbit.Fitbit(client_id, client_secret, oauth2=True,
access_token=access_token,
refresh_token=refresh_token)
Finally we can download Fitbit data using the API. Let's look at my sleep and step data from last Sunday as an example:
sleep_ts = authd_client.time_series('sleep/minutesAsleep', period='3m')
sleep_ts['sleep-minutesAsleep'][-7]
{'dateTime': '2016-03-13', 'value': '351'}
steps_ts = authd_client.time_series('activities/steps', period='3m')
steps_ts['activities-steps'][-7]
{'dateTime': '2016-03-13', 'value': '15468'}
Looks like I didn't sleep too much the night of Saturday to Sunday and I gathered more than 15k steps on Sunday (mostly playing Ultimate Frisbee, I presume).
Next, I would like to download additional data from Fitbit gathered over a longer period of time, store them in suitable data structures and create some basic visualizations.
For additional information regarding the Fitbit API and which data can be downloaded, check the API documentation. Also the python-fitbit documentation is worth a visit.