Coder Social home page Coder Social logo

python-fitbit's Introduction

python-fitbit

Build Status Coverage Status Requirements Status Gitter chat

Fitbit API Python Client Implementation

For documentation: http://python-fitbit.readthedocs.org/

Requirements

To use the library, you need to install the run time requirements:

sudo pip install -r requirements/base.txt

To modify and test the library, you need to install the developer requirements:

sudo pip install -r requirements/dev.txt

To run the library on a continuous integration server, you need to install the test requirements:

sudo pip install -r requirements/test.txt

python-fitbit's People

Contributors

bbodenmiller avatar bengt avatar brad avatar cc7768 avatar dpoirier avatar edwardbetts avatar glow-mdsol avatar grokcode avatar issackelly avatar jamieinfinity avatar jliphard avatar karthikbgl avatar lmancini avatar mariosangiorgio avatar mtoshi avatar myshen avatar percyperez avatar randi120 avatar requires avatar rlane avatar silviot avatar skoczen avatar streeter avatar tchellomello avatar xuefanzhang avatar xuy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-fitbit's Issues

trouble with gather-keys

Hello,

I'm a newbie and I'm very confused, so apologies. I've tried three php wrappers and now I'm on my 2nd python wrapper, and I still can't seem to get log in to fitbit.

I'm typing in
python gather_keys_oauth2.py client_id=*** client_secret=***

This launches my browser and links me to fitbit's page, but I get the error message: "Developer information: unauthorized_client - Invalid client_id"

I've confirmed that it is the correct client_id. Can someone help explain what I might be doing wrong?

Thanks in advance!

force login/revoke access/programmatic access?

I'd like to (for example) implement the prompt parameter as listed in the documentation (https://dev.fitbit.com/docs/oauth2/#authorization-page) for a project I'm helping a client with. I'm trying to look through the package code, but it's not immediately apparent where I'd make edits, if any.

Alternatively, I'd like to be able to revoke access on demand, as it's sort of a pain having to remove cookies/browser history every time we need to switch user accounts (hence forcing the login prompt). Is this sort of thing currently possible in the current state of the package? Or would significant work need to be done? I could try to patch it myself if I had a better idea of how the parts worked together.

Lastly, I'm not sure if this is possible given what I've read on the Fitbit site, but would it be possible to skip the login completely and validate programmatically? It would be so that we could pull down information for multiple users at the same time/in the same pass. However, I'm not sure if this is possible given what is mentioned about embedding the authorization page, etc. Thanks!

Remove dependency on python-oauth2

The development of python-oauth2 stopped dead about 2 years ago.

There are currently two CVEs (security issues) reported for python-oauth2.

https://security-tracker.debian.org/tracker/source-package/python-oauth2

This means that python-fitbit is currently inheriting those security issues.

https://pypi.python.org/pypi/oauthlib would provide a secure alternative, and the upstream development is quite active. This was also the recommended library when I enquired on the debian-python mailing list.

https://security-tracker.debian.org/tracker/source-package/python-oauth2

Specifying a start or end time of midnight for intraday_time_series causes a TypeError

If you call the intraday_time_series method and specify a start time or end time of midnight (i.e. 00:00), a TypeError is thrown. Minimum working example:

import fitbit
from datetime import time
from secrets import consumer_key, consumer_secret, user_key, user_secret

client = fitbit.Fitbit(consumer_key, 
                       consumer_secret, 
                       resource_owner_key=user_key, 
                       resource_owner_secret=user_secret)
client.intraday_time_series("activities/steps", start_time=time(0,0), end_time=(23,59))

This behaviour is caused by lines 376 and 379 of api.py, i.e.

if start_time and not end_time:
    raise TypeError("You must provide an end time when you provide a start time")

if end_time and not start_time:
    raise TypeError("You must provide a start time when you provide an end time")

The problem is that if start_time = time(0,0), then it evaluates to False as a boolean (the same goes for end_time) so the check if start_time and ... will always evaluate to False. I think the idea here is to check that start_time is not equal to None, so the fix here should be pretty simple:

if start_time is not None and end_time is None:
    raise TypeError("You must provide an end time when you provide a start time")

if end_time is not None and start_time is None:
    raise TypeError("You must provide a start time when you provide an end time")

HTTPBadRequest: Can make request with `make_request`, but not `time_series`

Seems similar to #40? Very odd that the request succeeds with make_request, but not with time_series because it looks like (and verified) that the url formed within time_series is the same as used in the request (see below).

In [41]: print("{0}/{1}/{2}/{resource}/{base_date}/{end}.json".format(*uc._get_common_args(uid), resource="activities/steps", base_date="today", end="1d"))                    
https://api.fitbit.com/1/{uid}/activities/steps/today/1d.json

Here are calls to functions and their output

In [38]: uc.make_request("https://api.fitbit.com/1/user/%s/activities/steps/date/today/1d.json" %uid)                                                                          
Out[38]: {'activities-steps': [{'dateTime': '2016-01-01', 'value': '6382'}]}

In [39]: uc.time_series("/activities/steps", user_id=uid, period="1m")                                                                                                         
---------------------------------------------------------------------------
HTTPBadRequest                            Traceback (most recent call last)
<ipython-input-39-10999dd69a1a> in <module>()
----> 1 uc.time_series("/activities/steps", user_id=uid, period="1m")

/home/chase/Documents/Personal/colemanfitbitcompetition/python-fitbit/fitbit/api.py in time_series(self, resource, user_id, base_date, period, end_date)
    641             end=end
    642         )
--> 643         return self.make_request(url)
    644 
    645     def intraday_time_series(self, resource, base_date='today', detail_level='1min', start_time=None, end_time=None):

/home/chase/Documents/Personal/colemanfitbitcompetition/python-fitbit/fitbit/api.py in make_request(self, *args, **kwargs)
    360 
    361         method = kwargs.get('method', 'POST' if 'data' in kwargs else 'GET')
--> 362         response = self.client.make_request(*args, **kwargs)
    363 
    364         if response.status_code == 202:

/home/chase/Documents/Personal/colemanfitbitcompetition/python-fitbit/fitbit/api.py in make_request(self, url, data, method, **kwargs)
    228             raise HTTPServerError(response)
    229         elif response.status_code >= 400:
--> 230             raise HTTPBadRequest(response)
    231         return response
    232 

HTTPBadRequest: This request should use the https protocol.

I should be able to get what I want directly through make_request, but I thought I would bring this up.

Great package. Really appreciate y'all putting this together.

Problem with imports when I run ./fitbit/gather_keys_cli.py

Hi, if I try to gather keys I get the following error:

$./fitbit/gather_keys_cli.py KEY SECRET Traceback (most recent call last): File "./fitbit/gather_keys_cli.py", line 34, in <module> from api import FitbitOauthClient File "/Users/mariosangiorgio/FitBitHacks/python-fitbit/fitbit/api.py", line 9, in <module> from fitbit.exceptions import (BadResponse, DeleteError, HTTPBadRequest, ImportError: No module named fitbit.exceptions

I tracked down the issue to the fact that in api.py there is an import of fitbit.exceptions but when we execute gather_keys_cli.py we already are in the fitbit directory. In fact, the script import instruction is from api import FitbitOauthClient instead of from fitbit.api import FitbitOauthClient.

As a workaround, I moved the script outside the fitbit directory and changed the import accordingly. If it is a solution you like I can create a pull request.

Otherwise, if there is another better and more pythonic solution I'd be happy to adopt it.

OpenSSL: TypeError: buf must be a byte string?

Using the script

authd_client = fitbit.Fitbit('consumer_key', 'consumer_secret', oauth2=True, access_token='access_token', refresh_token='refresh_token')
authd_client.sleep()

I'm getting the following error from the OpenSSL library in my global config. Thinking it's a problem with libaries, I created a virtualenv and installed via pip install -r requirements/base.txt. I'm still getting the same problem.

Has anyone else experienced this issue?

(venv)fitbit ➤ python fit.py                                                                                                                   
Traceback (most recent call last):
  File "fit.py", line 19, in <module>
    client.sleep()
  File "/usr/local/lib/python2.7/dist-packages/fitbit/utils.py", line 38, in _curried
    return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
  File "/usr/local/lib/python2.7/dist-packages/fitbit/api.py", line 454, in _COLLECTION_RESOURCE
    return self.make_request(url, data)
  File "/usr/local/lib/python2.7/dist-packages/fitbit/api.py", line 362, in make_request
    response = self.client.make_request(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/fitbit/api.py", line 193, in make_request
    response = self._request(method, url, data=data, auth=auth, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/fitbit/api.py", line 180, in _request
    return self.session.request(method, url, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 362, in send
    timeout=timeout
  File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 516, in urlopen
    body=body, headers=headers)
  File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 308, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python2.7/httplib.py", line 1001, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.7/httplib.py", line 1035, in _send_request
    self.endheaders(body)
  File "/usr/lib/python2.7/httplib.py", line 997, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python2.7/httplib.py", line 850, in _send_output
    self.send(msg)
  File "/usr/lib/python2.7/httplib.py", line 826, in send
    self.sock.sendall(data)
  File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 208, in sendall
    return self.connection.sendall(data)
  File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 969, in sendall
    raise TypeError("buf must be a byte string")
TypeError: buf must be a byte string

fetch_request_token return an OAUTH error

Code used:

    parameters = {'oauth_callback': callback_url}
    oa = fitbit.Fitbit(self.CONSUMER_KEY, self.CONSUMER_SECRET)
    req_token = oa.client.fetch_request_token(parameters=parameters)

Exception: Invalid response {"errors":[{"errorType":"oauth","fieldName":"n/a","message":"oauth_problem=parameter_absent&oauth_parameters_absent=oauth_signature_method%26oauth_signature"}],"success":false}.

This is probably related with the recent changes to the OAUTH implementation at Fitbit. See https://groups.google.com/forum/?hl=en&lnk=gcimh#!topic/fitbit-api/M_5m9EiVDc8

I can not get the library to use OAuth2.

Hi,

I'm implementing Fitbit data fetching to our application.

While I was looking for how to do this I noticed your great library.

I have been testing you library today (just today).

I installed library with command 'easy_install fitbit' and it started to work.
After few testing I started to look how to actually gather the tokens.
I noticed from your documents that you have code to get tokens, but not much guides how to do this.
So I cloned your code and I found out that you have really nice example code in file 'gather_keys_oauth2.py'.

Now I have implemented similar procedure in my app.

I encountered problem while trying to use the tokens.
authd_client = fitbit.Fitbit(
consumer_key, #'<consumer_key>',
consumer_secret, #'<consumer_secret>',
oauth2=True,
access_token=token.get('access_token'), #,
refresh_token=token.get('refresh_token') #)

authd_client.client is <fitbit.api.FitbitOauthClient object at 0x645bfd0>

It seems that setting 'oauth2=True' does not do anything.

After while I decided just use your code in my code (so I'm not using the library).
And now it works !!!!!!

It seems there is some problem with binary file (https://pypi.python.org/pypi/fitbit/0.1.3).

Documentation inconsistent with implementation

Per the docs, I am creating my client as such:
client = fitbit.Fitbit(c_key, c_secret, key, secret)

Which gives me an error of:
TypeError: __init__() takes at most 4 arguments (5 given)

Looking at the code, I am assuming what was meant was this:
client = fitbit.Fitbit(c_key, c_secret, user_key=key, user_secret=secret)

Is that correct or am I misreading it?

foods() can't work

The api endpoint is /foods/log/date/...json so it can't be curried right with foods in the ressource list.

Exception (invalid response) on fetch_access_token()

Hi, I have an app that is using your library. Authentication was working fine until recently (I think Fitbit changed their OAuth) and now I'm having problems. Trying to do things by hand, this is what I run into.

fb = Fitbit(consumer_key=KEY, consumer_secret=SECRET, **kwargs)
parameters = {'oauth_callback':'http://www.google.com'}
token = fb.client.fetch_request_token(parameters)
oauth_url = fb.client.authorize_token_url(token)
oauth_url
u'https://www.fitbit.com/oauth/authorize?oauth_token=a5f9b2fe25c98f39097739d462d5c579'

(At this point I visit the oauth_url, sign in to Fitbit, hit allow, and get redirected to Google, then I copy the oauth_verifier string from the url)

oauth_verifier='3jss2283t791fb18fvdribg0n0'
fb.client.fetch_access_token(token, oauth_verifier)
Traceback (most recent call last):
File "", line 1, in
File "/Path/To/App/server/.env/lib/python2.6/site-packages/fitbit/api.py", line 142, in fetch_access_token
raise Exception("Invalid response %s." % response.content)
Exception: Invalid response {"errors":[{"errorType":"oauth","fieldName":"n/a","message":"oauth_problem=parameter_absent&oauth_parameters_absent=oauth_signature_method%26oauth_signature"}],"success":false}.

Any ideas on what's wrong?

Time series acting strange?

So the library seems to work great, but as soon as I try to call on time_series the authorisation seems to act up. Other calls don't seem to create this problem. I created user token using gather_keys_cli but the tokens the error returns aren't mine so i would assume these are incorrect created signatures instead of token?

print authd_client.time_series('/activities/steps/',period='7d')
File "/Users/heinzehavinga/Desktop/scraper/scraperNew/fitbit/api.py", line 363, in time_series
return self.make_request(url)
File "/Users/heinzehavinga/Desktop/scraper/scraperNew/fitbit/api.py", line 198, in make_request
response = self.client.make_request(_args, *_kwargs)
File "/Users/heinzehavinga/Desktop/scraper/scraperNew/fitbit/api.py", line 80, in make_request
raise HTTPUnauthorized(response)
fitbit.exceptions.HTTPUnauthorized: Invalid signature or token 'XXXXXXXXXXXXXX' or token 'YYYYYYYYYYYYYYY'

Import Error

Hi,

I can't seem to import the library in my Ubuntu.

Any idea?

$ uname -a
Linux jink 3.8.0-29-generic #42~precise1-Ubuntu SMP Wed Aug 14 15:31:16 UTC 2013 i686 i686 i386 GNU/Linux

$ python -i
Python 2.7.3 (default, Feb 27 2014, 20:00:17)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import fitbit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/fitbit/__init__.py", line 10, in <module>
    from .api import Fitbit, FitbitOauthClient
  File "/usr/local/lib/python2.7/dist-packages/fitbit/api.py", line 2, in <module>
    import requests
  File "/usr/local/lib/python2.7/dist-packages/requests/__init__.py", line 58, in <module>
    from . import utils
  File "/usr/local/lib/python2.7/dist-packages/requests/utils.py", line 23, in <module>
    from .compat import parse_http_list as _parse_list_header
  File "/usr/local/lib/python2.7/dist-packages/requests/compat.py", line 7, in <module>
    from .packages import charade as chardet
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/__init__.py", line 3, in <module>
    from . import urllib3
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/__init__.py", line 16, in <module>
    from .connectionpool import (
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py", line 12, in <module>
    from .util import resolve_cert_reqs, resolve_ssl_version, assert_fingerprint
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/__init__.py", line 18, in <module>
    from .timeout import (
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/timeout.py", line 4, in <module>
    from ..exceptions import TimeoutStateError
ImportError: cannot import name TimeoutStateError
>>>

getting missing access token parameter trying to refresh token

Hi,
I'm having an issue here, it might be because I'm a newbie at OAuth and python, or because I'm doing something wrong here, but anyway.
I'm trying to refresh my token and I'm getting the following message:

authd_client.client.refresh_token()

File "C...Python\Python35-32\lib\site-packages\fitbit\api.py", line 162, in refresh_token
auth=requests.auth.HTTPBasicAuth(self.client_id, self.client_secret)
File "C...\Python\Python35-32\lib\site-packages\requests_oauthlib\oauth2_session.py", line 301, in refresh_token
self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
File "C...\Python\Python35-32\lib\site-packages\oauthlib\oauth2\rfc6749\clients\base.py", line 409, in parse_request_body
_response
self.token = parse_token_response(body, scope=scope)
File "C...\Programs\Python\Python35-32\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 376, in parse_token_response

validate_token_parameters(params)

File "C...\Python\Python35-32\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 386, in validate_token_param
eters
raise MissingTokenError(description="Missing access token parameter.")
oauthlib.oauth2.rfc6749.errors.MissingTokenError: (missing_token) Missing access token parameter.

and this is how I'm trying:

authd_client = fitbit.Fitbit("ID", 'secret',
access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

authd_client.client.refresh_token()

I would like to know if it is a bug or what is my mistake here.
Thanks

Callback URL not being invoked properly

This library is great - you've been enormously helpful, thanks! I've been having having an issue with my callback URL that I haven't been able to solve and would like to see if you have any insight on it.

My callback URL redirects to http://www.fitbit.com/[my callback URL], rather than just the callback URL. Erasing the http://www.fitbit.com manually in the browser makes the rest of the code proceed smoothly, but that's not exactly a permanent solution.

I experimented with the suggestions here but no dice: #32

Any thoughts? Code is below.

def fitbit_connect(request, username=None):
    # Get a request token.
    current_site = Site.objects.get_current()
    callback_url = urllib.quote('https://' + current_site.domain + ':8000' \
                                '/fitbit_callback/?username=' + username)

    client = fitbit.FitbitOauthClient(settings.FIT_BIT_CONSUMER_KEY, settings.FIT_BIT_CONSUMER_SECRET, callback_uri=callback_url)
    token = client.fetch_request_token()
    authorize_url = client.authorize_token_url()
    request.session['token'] = token

    return HttpResponseRedirect(authorize_url)

def fitbit_callback(request):
    # user has granted access
    try:
        username=request.GET['username']
        username = re.match("(.*?)\?", username)
        username = username.group(1)
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return HttpResponse('User does not exist...')
    token = request.session['token']

    oauth_verifier = request.GET['oauth_verifier']
    client = fitbit.FitbitOauthClient(settings.FIT_BIT_CONSUMER_KEY, settings.FIT_BIT_CONSUMER_SECRET)
    access_token = client.fetch_access_token(oauth_verifier, token)

    profile = user.profile
    profile.fitbit_access_token = access_token
    url = 'activity_stats'
    resp = get_fitbit_json_result(profile.fitbit_access_token, url, 'POST')
    profile.save()
    from dashboard.models import UserProfile
    user_profile = UserProfile
    return HttpResponseRedirect(reverse(
                                'admin:{}_{}_changelist'.format(
                                            user_profile._meta.app_label,
                                            user_profile._meta.module_name)))

json file format for log_activity

Hi,
I'm trying to use log_activity function but bad request exception is always caught
fitbit.exceptions.HTTPBadRequest: Either "activityId" or "activityName" should be present

my json file is the same one as in the api example
{ "activityLog":{ "activityId":12030, "activityParentId":90009, "calories":197, "description":"5 mph (12 min/mile)", "distance":3.34, "duration":1800000, "isFavorite":false, "logId":132394, "name":"Running", "startTime":"12:20", "steps":2970 } }

how I read the file

data = [] with open('log_activity') as f: data = json.load(f) print(data) authd_client.log_activity(data)
is there any issue with my code/file
thanks a lot

need to reauth too often?

I'm a bit of an oauth2 noob, so sorry if this is a moronic question.

Using the branch with the oauth2 fix, I'm grabbing the credentials and storing them in a config file. Then I'm loading them when I want to access the API. I've got some code to download all the user's fitbit history (based on the old dump.py example). When I hit the API rate limit, I wait until the next hour, but at that time my tokens have expired. I thought that the API itself should be handling this case...

Problem getting intraday HR from Charge HR

Hi Brad, me again - sorry

I want to read out the HR from Fitbit Charge HR but I always run into this ...
Traceback (most recent call last):
File "fitbit_heartrate.py", line 12, in
intradayH = authd_client.intraday_time_series('activities/heart', base_date = 'today', detail_level = '1min')
File "/usr/local/lib/python2.7/dist-packages/fitbit-0.1.3-py2.7.egg/fitbit/api.py", line 389, in intraday_time_series
return self.make_request(url)
File "/usr/local/lib/python2.7/dist-packages/fitbit-0.1.3-py2.7.egg/fitbit/api.py", line 201, in make_request
response = self.client.make_request(_args, *_kwargs)
File "/usr/local/lib/python2.7/dist-packages/fitbit-0.1.3-py2.7.egg/fitbit/api.py", line 96, in make_request
raise HTTPBadRequest(response)
fitbit.exceptions.HTTPBadRequest: Resource owner is required

I am calling it like:
import fitbit
import json

CLIENT_KEY = '7644256......99106bc0d90e'
CLIENT_SECRET = '87eacfb......6ac33c91e1'
ACCESS_TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0......x7tDE1Y6SB7q3c_Mrc'
REFRESH_TOKEN = 'cac2ebab561434178fa104f.....027553eb6fde84df4db49af060'

authd_client = fitbit.Fitbit(CLIENT_KEY, CLIENT_SECRET, oauth2=True, access_token=ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)

intradayH = authd_client.intraday_time_series('activities/heart', base_date = 'today', detail_level = '1min')

f = open('datadumpHeart.json', 'w')
json.dump(intradayH, f)

Do you have an idea for this?
Thanks
Robert

Oauth2 invalid consumer key && Resource Owner is required

Hey, I was wondering if I could get some help.

I'm not able to access fitbit resources and I'm sure the problem is my workflow.

I have set up my dev account (personal) with read&write permissions.
I have my consumer key and secret as well as my client ID. I am quite sure though that the consumer key is for oauth1 and client_id is for oauth2.

The supplied script ./gather_keys_oauth2.py provided the access and refresh tokens.

Making an instance of Fitbit with oauth2 provided me two errors. My first error is an invalid consumer key when using oauth2.

Line 327 in api.py suggests to handle the object as follows.

oauth2: Fitbit(id, secret, oauth2=True, access_token=token, refresh_token=token)

I used this as a basis in my script. All variables are defined above and correct.
client = fitbit.Fitbit(client_id, client_secret, oauth2=True, access_token=a_token, refresh_token=r_token)

When I try and access data using client.sleep(). I get the following error:
HTTPUnauthorized: Invalid consumer key:

Logically, I enter my consumer key instead of client ID. Now I get the error:
HTTPBadRequest: Resource owner is required

Comments in the Api.py mentions there are 7 parameters that should be passed. What would the other two or three parameters be? I cannot seem to find any documentation on this?

"Create a FitbitOauth2Client object. Specify the first 7 parameters if you have them to access user data."

Thank you in advanced!

Import error

I am a novice, and I am having trouble importing Fitbit library. Getting import errors with init.py and api.py. Running Python 2.7.11 on a Windows 10 machine. Funny thing is the import is working fine on a Windows 7 machine running Python 2.7.6. Any suggestions other than setting up virtualenv?

Heart rate based on OAuth 2.0

Hi!
Fitbit released OAuth 2.0 which is the base to retrieve Heart Rate data as far as I have understood it. Could you please integrate this OAuth 2.0 procedure. I am currently running it like shown, but I don't get heart rate!
robertheinze_ pi_raspberrypi____downloads_benallard-galileo-65f67e191699_galileo ssh _128x37

gather_keys_oauth2

I don’t know why but my gather_keys_oauth2.py stands still with “Bus STARTED” forever.
What parameters do you call it with? Client (Consumer) Key and the Client (Consumer) Secret-is this correct? Are there any other precautions to be done?

Callback URL not being invoked

I am trying to integrate the FITBIT api in which i managed to get auth_token and redirect the user for Authorization. While creating the Fitbit() i am setting the callback_uri. But, after completing the authorization the FitBit API is not invoking my callback service.

Please pardon my ignorance and help me to deal with this issue.

I am using Web2Py framework and below is my code.

def index():
    callback_uri=getHost()+URL('callback','completeAuthorization')
    from fitbit import Fitbit
    from requests_oauthlib import OAuth1Session
    client_kwargs = {
            'client_key': 'c8ca82f890c44a969cc3524b7c342e8b',
            'client_secret': '7bf3dd8b933144e2bbe2c7971d46e3ae',
            'user_key': None,
            'user_secret': None,
            'callback_uri': callback_uri
        }
    fb = Fitbit(**client_kwargs)
    retval = fb.client.fetch_request_token()
    url='https://api.fitbit.com/oauth/authorize?oauth_token='+retval.get('oauth_token')+'&callback_uri='+callback_uri
    print callback_uri
    redirect(url)
    return dict(message=url)

def completeAuthorization():
    print request
    print request.vars
    print request.args
    oauth_token=request.vars.oauth_token
    oauth_verifier=request.vars.oauth_verifier
    return locals

def getHost():
    request_host_uri = URL(args=request.args, vars=request.vars, host=True)
    request_uri = URL(args=request.args, vars=request.vars, host=False)
    parts = request_host_uri.split(request_uri)
    host = parts[0]
    return str(host)

EDIT(brad): I wrapped your code to make it easier to read

Cannot retrieve goals

How do I retrieve a user's goals for body weight, water or activities? They are in the collection resource part of the API, so I tried authd_client.__COLLECTION_RESOURCE('foods/log/water'). However, this appends today's date to the URL and the resulting URL is eg https://api.fitbit.com/1/user/-/foods/log/water/goal/date/2014-12-28.json. The API wants the URL to be just GET /<api-version>/user/-/foods/log/water/goal.<response-format> instead (see https://wiki.fitbit.com/display/API/API-Get-Water-Goal), so I'm getting an HttpBadRequest exception.

Docs link to wiki.fitbit.com and not dev.fitbit.com

Hi!

Thanks for making this package, it's really awesome 😄

The most updated Fitbit API docs are at: dev.fitbit.com. However, I noticed that the python-fitbit docs all point to wiki.fitbit.com. Will you accept a PR fixing this problem?

Body Log missing/undocumented?

Hey there,

Loving the library, but running into one snag - it seems like one API endpoint is missing - the body log. This provides all the readings for a scale, etc.
https://wiki.fitbit.com/display/API/API-Get-Body-Weight

I read through the docs a number of time, and started digging into the library code, but figured I'd just ask before tossing a ton of time at it. Am I missing where it lives?

Thanks!
-Steven

Unable to find 'user_key'/ 'user_secret' via 'gather_keys_cli.py'

Hi folks,

How do i find the 'user_key'/ 'user_secret' used in the :

authd_client = fitbit.Fitbit('<consumer_key>', '<consumer_secret>', resource_owner_key='<user_key>', resource_owner_secret='<user_secret>')

./gather_keys_cli.py provides this information only

RESPONSE
{ u'encoded_user_id': u'alpha',
u'oauth_token': u'xyz',
u'oauth_token_secret': u'abc'
}

How do i use it to get the 'user_key' and 'user_secret' params? Thanks in advance.

Put the library on Pypi

The library is really nice and do a great job but it would be better if it could available on pypi !
Thanks a lot !

OAuth2 "missing access token" with with OAuth 2.0 after gather_keys_cli.py passes

Hi everyone,

I'm able to get user access_token (i.e., user_key) and refresh_token (i.e., user_secret) from gather_keys_oauth2.py. (For background my requests-oauthlib is on version 0.7.0)

But when I try to do:

authd_client = fitbit.Fitbit(consumer_key, consumer_secret, user_key=access_token, user_secret=refresh_token)
 
body_stats = authd_client._COLLECTION_RESOURCE('body')

I don't get errors when I run:
authd_client = fitbit.Fitbit(consumer_key, consumer_secret, user_key=access_token, user_secret=refresh_token)

But the errors show up when I run: body_stats = authd_client._COLLECTION_RESOURCE('body')

See below

File "simple_get_data.py", line 30, in <module>
    body_stats = authd_client._COLLECTION_RESOURCE('sleep')
  File "/Users/lpina/Repositories/python-fitbit/fitbit/api.py", line 324, in _COLLECTION_RESOURCE
    return self.make_request(url, data)
  File "/Users/lpina/Repositories/python-fitbit/fitbit/api.py", line 232, in make_request
    response = self.client.make_request(*args, **kwargs)
  File "/Users/lpina/Repositories/python-fitbit/fitbit/api.py", line 70, in make_request
    response = self._request(method, url, data=data, auth=auth, **kwargs)
  File "/Users/lpina/Repositories/python-fitbit/fitbit/api.py", line 57, in _request
    return self.session.request(method, url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 474, in request
    prep = self.prepare_request(req)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 407, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/Library/Python/2.7/site-packages/requests/models.py", line 306, in prepare
    self.prepare_auth(auth, url)
  File "/Library/Python/2.7/site-packages/requests/models.py", line 518, in prepare_auth
    r = auth(self)
  File "/Library/Python/2.7/site-packages/requests_oauthlib/oauth2_auth.py", line 35, in __call__
    http_method=r.method, body=r.body, headers=r.headers)
  File "/Library/Python/2.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 191, in add_token
    raise ValueError("Missing access token.")
ValueError: Missing access token.

Thanks!

Refresh token

After my token expired, I was unable to refresh it. Seems related to how the requests-oauthlib package is being called.

I will probably look at this again later -- though today is my first time interacting with oauth so I don't know how much help I'll be. Will update if I learn more.

In [68]: uc.client.refresh_token()                                                                                                                                     
---------------------------------------------------------------------------
MissingTokenError                         Traceback (most recent call last)
<ipython-input-68-b899b2fcc311> in <module>()
----> 1 uc.client.refresh_token()

/home/chase/Documents/Personal/colemanfitbitcompetition/python-fitbit/fitbit/api.py in refresh_token(self)
    290             self.refresh_token_url,
    291             refresh_token=self.token['refresh_token'],
--> 292             headers=headers)
    293         return self.token
    294 

/home/chase/Programming/anaconda3/envs/cfbc/lib/python3.5/site-packages/requests_oauthlib/oauth2_session.py in refresh_token(self, token_url, refresh_token, body, auth, timeout, headers, verify, **kwargs)
    297             r = hook(r)
    298 
--> 299         self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
    300         if not 'refresh_token' in self.token:
    301             log.debug('No new refresh token given. Re-using old.')

/home/chase/Programming/anaconda3/envs/cfbc/lib/python3.5/site-packages/oauthlib/oauth2/rfc6749/clients/base.py in parse_request_body_response(self, body, scope, **kwargs)
    407         .. _`Section 7.1`: http://tools.ietf.org/html/rfc6749#section-7.1
    408         """
--> 409         self.token = parse_token_response(body, scope=scope)
    410         self._populate_attributes(self.token)
    411         return self.token

/home/chase/Programming/anaconda3/envs/cfbc/lib/python3.5/site-packages/oauthlib/oauth2/rfc6749/parameters.py in parse_token_response(body, scope)
    374 
    375     params = OAuth2Token(params, old_scope=scope)
--> 376     validate_token_parameters(params)
    377     return params
    378 

/home/chase/Programming/anaconda3/envs/cfbc/lib/python3.5/site-packages/oauthlib/oauth2/rfc6749/parameters.py in validate_token_parameters(params)
    384 
    385     if not 'access_token' in params:
--> 386         raise MissingTokenError(description="Missing access token parameter.")
    387 
    388     if not 'token_type' in params:

MissingTokenError: (missing_token) Missing access token parameter.

OAuth2 "missing access token" with gather_keys_oauth2.py

Hi,

First of all: thanks a lot for this package, it seems to work really well with oauth1.

Second: I want to use it using OAuth2 (which will be mandatory from March 2016 according to Fitbit), but I can't get my access token using your "gather_keys_oauth2.py" script.

I chose http:/127.0.0.1:8080/ as a callback url, and when I authorize access on the Fitbit page I only get this error:
(Of course client_key is the one provided for OAuth2 on my app page, and client_secret is verified to work using OAuth1)

ERROR: Missing access token parameter.
Please check that you are using the correct client_secret

You can close this window

  File "gather_keys_oauth2.py", line 46, in index
    self.oauth.fetch_access_token(code, self.redirect_uri)

  File "C:\Users\Fabien P\Desktop\python-fitbit-master\fitbit\api.py", line 275, in fetch_access_token
    self.token = auth.fetch_token(self.access_token_url, headers=self.auth_header, code=code)

  File "C:\Anaconda3\lib\site-packages\requests_oauthlib-0.6.0-py3.4.egg\requests_oauthlib\oauth2_session.py", line 232, in fetch_token
    self._client.parse_request_body_response(r.text, scope=self.scope)

  File "C:\Anaconda3\lib\site-packages\oauthlib-1.0.3-py3.4.egg\oauthlib\oauth2\rfc6749\clients\base.py", line 409, in parse_request_body_response
    self.token = parse_token_response(body, scope=scope)

  File "C:\Anaconda3\lib\site-packages\oauthlib-1.0.3-py3.4.egg\oauthlib\oauth2\rfc6749\parameters.py", line 376, in parse_token_response
    validate_token_parameters(params)

  File "C:\Anaconda3\lib\site-packages\oauthlib-1.0.3-py3.4.egg\oauthlib\oauth2\rfc6749\parameters.py", line 386, in validate_token_parameters
    raise MissingTokenError(description="Missing access token parameter.")

I don't get what's the point of this error. This routine is done to fetch an access token from Fitbit, so how could I have one at this stage ?

But maybe I did something the wrong way, I am quite new to all this API stuff...
I though that it may be a problem with the version of my oauth2 package. If so, could you tell me what version to use ?

Any idea ?

Best,
Fabien

Support for Get-Intraday-Time-Series API

Can you add support for intraday time series API?
https://wiki.fitbit.com/display/API/API-Get-Intraday-Time-Series

I tried to do it myself, but it returns a 500. For example, to get intraday steps with a detail level of 1min, I make a request to the following:

url='https://api.fitbit.com/1/user/-/activities/distance/date/2013-10-01/2013-10-01/1min.json'
fitbit_client.make_request(url)

If I omit the '1min' part, it just returns the result of the time series API.

can't be installed on debian

[juke@jhost:~] % su -c "pypi-install fitbit"
Mot de passe :
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
running the following command in directory: deb_dist/tmp_py2dsc/fitbit-0.1.2
/usr/bin/python setup.py --command-packages stdeb.command sdist_dsc --dist-dir=/tmp/tmp7Vs_OP/deb_dist --use-premade-distfile=/tmp/tmp7Vs_OP/fitbit-0.1.2.tar.gz bdist_deb
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
running sdist_dsc
running egg_info
writing requirements to fitbit.egg-info/requires.txt
writing fitbit.egg-info/PKG-INFO
writing top-level names to fitbit.egg-info/top_level.txt
writing dependency_links to fitbit.egg-info/dependency_links.txt
reading manifest file 'fitbit.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'fitbit.egg-info/SOURCES.txt'
CALLING dpkg-source -b fitbit-0.1.2 fitbit_0.1.2.orig.tar.gz (in dir /tmp/tmp7Vs_OP/deb_dist)
dpkg-source: info: utilisation du format source « 3.0 (quilt) »
dpkg-source: info: construction de fitbit à partir de ./fitbit_0.1.2.orig.tar.gz
dpkg-source: info: construction de fitbit dans fitbit_0.1.2-1.debian.tar.gz
dpkg-source: info: construction de fitbit dans fitbit_0.1.2-1.dsc
dpkg-buildpackage: avertissement: utilisation d'une commande pour obtenir les privilèges administrateur en tant qu'administrateur
dpkg-buildpackage: paquet source fitbit
dpkg-buildpackage: version source 0.1.2-1
dpkg-buildpackage: source changé par Issac Kelly and ORCAS [email protected]
dpkg-source --before-build fitbit-0.1.2
fakeroot debian/rules clean
dh clean --with python2 --buildsystem=pybuild
dh_testdir -O--buildsystem=pybuild
dh_auto_clean -O--buildsystem=pybuild
I: pybuild base:170: python2.7 setup.py clean
running clean
removing '/tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build' (and everything under it)
'build/bdist.linux-x86_64' does not exist -- can't clean it
'build/scripts-2.7' does not exist -- can't clean it
dh_clean -O--buildsystem=pybuild
dpkg-source -b fitbit-0.1.2
dpkg-source: info: utilisation du format source « 3.0 (quilt) »
dpkg-source: info: construction de fitbit à partir de ./fitbit_0.1.2.orig.tar.gz
dpkg-source: avertissement: suppression du répertoire fitbit.egg-info ignorée
dpkg-source: avertissement: suppression du fichier fitbit.egg-info/requires.txt ignorée
dpkg-source: avertissement: suppression du fichier fitbit.egg-info/SOURCES.txt ignorée
dpkg-source: avertissement: suppression du fichier fitbit.egg-info/PKG-INFO ignorée
dpkg-source: avertissement: suppression du fichier fitbit.egg-info/top_level.txt ignorée
dpkg-source: avertissement: suppression du fichier fitbit.egg-info/dependency_links.txt ignorée
dpkg-source: info: construction de fitbit dans fitbit_0.1.2-1.debian.tar.gz
dpkg-source: info: construction de fitbit dans fitbit_0.1.2-1.dsc
dpkg-genchanges -S -sa >../fitbit_0.1.2-1_source.changes
dpkg-genchanges: inclusion du code source original dans l'envoi (« upload »)
dpkg-source --after-build fitbit-0.1.2
dpkg-buildpackage: envoi complet (inclusion du code source d'origine)
dpkg-source: avertissement: extraction d'un paquet source non signé (fitbit_0.1.2-1.dsc)
dpkg-source: info: extraction de fitbit dans fitbit-0.1.2
dpkg-source: info: extraction de fitbit_0.1.2.orig.tar.gz
dpkg-source: info: extraction de fitbit_0.1.2-1.debian.tar.gz
running bdist_deb
dpkg-buildpackage: avertissement: utilisation d'une commande pour obtenir les privilèges administrateur en tant qu'administrateur
dpkg-buildpackage: paquet source fitbit
dpkg-buildpackage: version source 0.1.2-1
dpkg-buildpackage: source changé par Issac Kelly and ORCAS [email protected]
dpkg-buildpackage: architecture hôte amd64
dpkg-source --before-build fitbit-0.1.2
fakeroot debian/rules clean
dh clean --with python2 --buildsystem=pybuild
dh_testdir -O--buildsystem=pybuild
dh_auto_clean -O--buildsystem=pybuild
I: pybuild base:170: python2.7 setup.py clean
running clean
removing '/tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build' (and everything under it)
'build/bdist.linux-x86_64' does not exist -- can't clean it
'build/scripts-2.7' does not exist -- can't clean it
dh_clean -O--buildsystem=pybuild
debian/rules build
dh build --with python2 --buildsystem=pybuild
dh_testdir -O--buildsystem=pybuild
dh_auto_configure -O--buildsystem=pybuild
I: pybuild base:170: python2.7 setup.py config
running config
dh_auto_build -O--buildsystem=pybuild
I: pybuild base:170: /usr/bin/python setup.py build
running build
running build_py
creating /tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build/fitbit
copying fitbit/utils.py -> /tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build/fitbit
copying fitbit/exceptions.py -> /tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build/fitbit
copying fitbit/init.py -> /tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build/fitbit
copying fitbit/api.py -> /tmp/tmp7Vs_OP/deb_dist/fitbit-0.1.2/.pybuild/pythonX.Y_2.7/build/fitbit
running egg_info
creating fitbit.egg-info
writing requirements to fitbit.egg-info/requires.txt
writing fitbit.egg-info/PKG-INFO
writing top-level names to fitbit.egg-info/top_level.txt
writing dependency_links to fitbit.egg-info/dependency_links.txt
writing manifest file 'fitbit.egg-info/SOURCES.txt'
reading manifest file 'fitbit.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'fitbit.egg-info/SOURCES.txt'
dh_auto_test -O--buildsystem=pybuild
I: pybuild base:170: python2.7 setup.py test
running test
running egg_info
writing requirements to fitbit.egg-info/requires.txt
writing fitbit.egg-info/PKG-INFO
writing top-level names to fitbit.egg-info/top_level.txt
writing dependency_links to fitbit.egg-info/dependency_links.txt
reading manifest file 'fitbit.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'fitbit.egg-info/SOURCES.txt'
running build_ext
Traceback (most recent call last):
File "setup.py", line 42, in
'Programming Language :: Python :: Implementation :: PyPy'
File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/usr/lib/python2.7/dist-packages/setuptools/command/test.py", line 137, in run
self.with_project_on_sys_path(self.run_tests)
File "/usr/lib/python2.7/dist-packages/setuptools/command/test.py", line 117, in with_project_on_sys_path
func()
File "/usr/lib/python2.7/dist-packages/setuptools/command/test.py", line 146, in run_tests
testLoader = loader_class()
File "/usr/lib/python2.7/unittest/main.py", line 94, in init
self.parseArgs(argv)
File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
self.createTests()
File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
self.module)
File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
module = import('.'.join(parts_copy))
ImportError: No module named fitbit_tests
E: pybuild pybuild:256: test: plugin distutils failed with: exit code=1: python2.7 setup.py test
dh_auto_test: pybuild --test -i python{version} -p 2.7 --dir . returned exit code 13
make: *** [build] Erreur 13
dpkg-buildpackage: erreur: debian/rules build a produit une erreur de sortie de type 2
Traceback (most recent call last):
File "setup.py", line 42, in
'Programming Language :: Python :: Implementation :: PyPy'
File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/usr/lib/python2.7/dist-packages/stdeb/command/bdist_deb.py", line 48, in run
util.process_command(syscmd,cwd=target_dirs[0])
File "/usr/lib/python2.7/dist-packages/stdeb/util.py", line 169, in process_command
check_call(args, cwd=cwd)
File "/usr/lib/python2.7/dist-packages/stdeb/util.py", line 45, in check_call
raise CalledProcessError(retcode)
stdeb.util.CalledProcessError: 2
ERROR running: /usr/bin/python setup.py --command-packages stdeb.command sdist_dsc --dist-dir=/tmp/tmp7Vs_OP/deb_dist --use-premade-distfile=/tmp/tmp7Vs_OP/fitbit-0.1.2.tar.gz bdist_deb
ERROR in deb_dist/tmp_py2dsc/fitbit-0.1.2
Traceback (most recent call last):
File "/usr/bin/pypi-install", line 67, in
main()
File "/usr/bin/pypi-install", line 53, in main
subprocess.check_call(cmd, shell=True)
File "/usr/lib/python2.7/subprocess.py", line 540, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'py2dsc-deb fitbit-0.1.2.tar.gz' returned non-zero exit status 1

OAuth2 "intraday_time_series" error

Hi,

When I try:

client.intraday_time_series('heart')  # client is my fitbit.Fitbit() instance with OAuth2 authentification

I get this error:

HTTPBadRequest: Invalid time series resource path: /heart

By comparison when I tried to manually get this kind of data using another Python Fitbit API client (https://github.com/magnific0/FitBit.py) I successfully get data. However your client is more complete and I would prefer to get it working.

Any idea ?

Best,
Fabien

make_request inside FitbitOauth2Client does not handle refresh on expired token correctly

Hi there,

I think there is a problem with token refreshing. On expired_token, fitbit.exceptions.HTTPUnauthorized: Access token expired is still being thrown instead of handled correctly. https://github.com/orcasgit/python-fitbit/blob/master/fitbit/api.py#L82.

Inside the if condition, it checks d['errors'][0]['errorType'] == 'oauth' and ... and calls self.refresh_token() when that condition is met, but the errorType is 'expired_token' not 'oauth'. This is the JSON body:

{u'errors': [{u'errorType': u'expired_token',
u'message': u'Access token expired: [omitting_token_string here]. Visit https://dev.fitbit.com/docs/oauth2 for more information on the Fitbit Web API authorization process.'}],
u'success': False}

As a result it's never retried and we get the access token expired exception later again.

Let me know if my understanding of how this works/doesn't work is correct :)...

Is the Quickstart example still working?

I tried to run:

import fitbit
def main():
    consumer_key = 'xxx'  # key and secret collected from dev.fitbit.com site
    consumer_secret = 'xxx'
    unauth_client = fitbit.Fitbit(consumer_key, consumer_secret)
    print unauth_client.activities()

And got (with the 0.0.2 release as installed using pip today on a Mac Mavericks machine):
Traceback (most recent call last):
File "./fb.py", line 27, in
main()
File "./fb.py", line 23, in main
print unauth_client.activities()
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/fitbit/utils.py", line 38, in _curried
return curried_func((args+moreargs), *_dict(kwargs, *_morekwargs))
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/fitbit/api.py", line 297, in _COLLECTION_RESOURCE
return self.make_request(url, data)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/fitbit/api.py", line 201, in make_request
response = self.client.make_request(_args, **kwargs)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/fitbit/api.py", line 73, in make_request
raise HTTPBadRequest(response)
fitbit.exceptions.HTTPBadRequest

I also tried to run the authorized example and also got the HTTPBadRequest.

Thanks!

Problem with SSL?

Don't think this library would work anymore because as of in early November 2014 Fitbit changed the API so that it requires https. Looks like the links in the files use https; is anyone else having any trouble getting this to work?

Does the host server also need to be using https? My localhost right now isn't set up for SSL.
Getting: TypeError: must be _socket.socket, not socket

Deploying to an online server (google app engine) doesn't seem to help; if I try something like the quickstart with .activities() on the unauthorized client it gives me a 500 server error.
(Note: I have no idea what I'm doing)

How to get resource_owner_key / resource_owner_secret?

Hi, I have trouble getting the resource_owner_key / resource_owner_secret.

I used the customer_key & customer_secret from the https://www.fitbit.com/dev/dev.

And I tried the ./gather_keys_cli.py, but it doesn't seem to provide the information.

Any help?

# You'll have to gather the user keys on your own, or try
# ./gather_keys_cli.py <consumer_key> <consumer_secret> for development
authd_client = fitbit.Fitbit('<consumer_key>', '<consumer_secret>', resource_owner_key='<user_key>', resource_owner_secret='<user_secret>')
authd_client.sleep()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.