Today I have been experimenting with the Fitbit API.

Here are some rather amateurish steps for getting data from Fitbit’s “cloud”.
Simple Client Setup for Public Data
1. Get and setup a Fitbit product.
I have access to a set of Fitbit scales (the “Aria”). The Fitbit Force looks quite good; I may get one of those when they are launched in the UK to record steps.
2. Register an “App”
Goto https://dev.fitbit.com. Login using your Fitbit password from 1). Click the link to add an “app”.
3. Setup Libraries
Install oauth2:
sudo pip install oauth2
Clone python-fitbit:
mkdir Healthcare cd Healthcare git clone https://github.com/orcasgit/python-fitbit.git
4. Record Consumer Key & Secret
After registering your “app” in 2) above, you have access to a “Consumer Key” and a “Consumer Secret”. You can access these details by going to “Manage My Apps”. I then store these in a “config.ini” file I keep in my working project directory. For example:
[Login Parameters] C_KEY=*key_string* C_SECRET=*secret_string*
5. Access Public Data
With the client variables we can access public data on Fitbit.
import fitbit import ConfigParser #Load Settings parser = ConfigParser.SafeConfigParser() parser.read('config.ini') consumer_key = parser.get('Login Parameters', 'C_KEY') consumer_secret = parser.get('Login Parameters', 'C_SECRET') #Setup an unauthorised client (e.g. with no user) unauth_client = fitbit.Fitbit(consumer_key, consumer_secret) #Get data for a user user_params = unauth_client.user_profile_get(user_id='1ABCDE')
You can get your user ID by accessing your Fitbit profile page. It is displayed in a URL just above any photo you may have. The last command returns a JSON string similar to this one:
{u'user': {u'city': u'', u'strideLengthWalking': 0, u'displayName': u'USERNAME', u'weight': 121.5, u'country': u'', u'aboutMe': u'', u'strideLengthRunning': 0, u'height': 0, u'timezone': u'UTC', u'dateOfBirth': u'', u'state': u'', u'encodedId': u'1ABCDE', u'avatar': u'https://pic_url.jpg', u'gender': u'NA', u'offsetFromUTCMillis': 0, u'fullName': u'', u'nickname': u'', u'avatar150': u'https://pic_url.jpg'}}
As I am only looking at getting a current weight reading (as taken from the last Aria scales measurement) I could stop here, as long as I have made my “body” data public (viewable by “Anyone” on the Fitbit profile > privacy page). However, as I wanted to get a BMI and body fat reading I continued with user authentication.
User Authenication
The python-fitbit library has a routine called gather_keys_cli.py. I followed this routine in iPython to get the user key and secret for my own Fitbit account.
1. Fetch Request Token
client = fitbit.FitbitOauthClient(consumer_key, consumer_secret) token = client.fetch_request_token() print 'FROM RESPONSE' print 'key: %s' % str(token.key) print 'secret: %s' % str(token.secret) print 'callback confirmed? %s' % str(token.callback_confirmed) print ''
2. Allow Access to User Fitbit Account
I first followed the steps:
print '* Authorize the request token in your browser' print '' print 'open: %s' % client.authorize_token_url(token) print ''
I had registered my callback URL as http://localhost/callback. I had not actually implemented a request handler for this URL on my local machine. However, I learnt this was not a problem – the parameters I needed were included in the callback URL. Even though the page got a ‘404’ I could still see and extract the ‘verifier’ parameter from the URL in the browser.
3. Get User Key and Secret
First I stored the ‘verifier’ parameter from the URL as a string (verifier = “*parameterfromURL*”). Then I ran these steps to get the user key and secret:
print '* Obtain an access token ...' print '' print 'REQUEST (via headers)' print '' token = client.fetch_access_token(token, verifier) print 'FROM RESPONSE' print 'key: %s' % str(token.key) print 'secret: %s' % str(token.secret) print ''
4. Save User Key and Secret and Use in Request
The last step is to save the user key and secret in the “config.ini” file. I saved these as “U_KEY” and “U_SECRET” in a similar manner to the consumer key and secret. Hence, these variables could be retrieved by calling:
user_key = parser.get('Login Parameters', 'U_KEY') user_secret = parser.get('Login Parameters', 'U_SECRET')
Finally, we can use both sets of keys and secrets to access the more detailed user data:
authd_client = fitbit.Fitbit(consumer_key, consumer_secret, user_key=user_key, user_secret=user_secret) body_stats = authd_client._COLLECTION_RESOURCE('body')
Todo
Some further work includes:
- Adapting the python-fitbit routines for the iHealth API.
- Building a script that gets data and imports into a website datastore.
- Using the body data to alter a SVG likeness.
I’m stuck on step 2…
I get a reply, a URL
I copy and paste that on my browser
Then I click the allow button
What do I do next?
Thanks
I think on the App configuration on the Fitbit developer site there’s an option to add a “callback URL”. This is the URL that loads after you click the “allow” button. I entered a made up URL: http://localhost/callback.
This would try to look up a path on my machine but fail (as I don’t have a web-server handling requests at /callback. However, if you look at the URL in your browser address bar (e.g. without clicking away) you should see a long string as a URL parameter (beginning ?). Copy and paste the URL including this string into a text file or the like and manual extract the callback token value.
Hi Ben,
I’m a little stuck on this part as well. I’m led to a URL of the format http://localhost/callback?oauth_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&oauth_verifier=xxxxxxxxxxxxxxxxxxxxxxxxxx
When I set verifier to the string after “oath_verifier” and try running my program, I get the error “AttributeError: ‘str’ object has no attribute ‘get'”. Am I missing something here?
Thanks!
Miles
Thank you for taking the time to make this this, Ben! Very helpful 🙂
This is awesome! I have been struggling with this for a few days. I am now all the way up to the point where the web browser redirects back to my site and gives me the values of oauth_token= &oauth_verifier=. I do not understand what to do now…
How does that become the client key and secret?
File “C:\Users\C3P0\workspace\SY1415\myFitbit.py”, line 76, in
token = client.fetch_access_token(token, verifier)
File “C:\Python27\lib\site-packages\fitbit\api.py”, line 127, in fetch_access_token
self.resource_owner_key = token.get(‘oauth_token’)
AttributeError: ‘unicode’ object has no attribute ‘get’
Jeff, how did you resolve the error on self.resource_owner_key = token.get(‘oauth_token’)? I successfully got the callback to retrieve oauth_verifier but stuck on Step 3.
Thanks.
Thanks for posting all these instructions – not sure how people figure all this out!
Great work – I used your instructions as the starting point and just updated things for OAuth 2.0, so people can start to look at heart rate data. Instructions are here: http://janliphardt.com/2015/06/14/fitbit-api-and-high-resolution-heart-rate-data/
Hey, thank you for the guide. I am trying to download my heart beat from my account but I still have to understand how to… Anyway, following your guide I still have some trouble. When I try to do the Fetch Request Token step I end up with the error:
AttributeError: ‘dict’ object has no attribute ‘key’. I guess this is because in the “token” dict there is no “key” key. Does your code is still running? Hope you can find the time to answer.