Search code examples
rapirestoauth-2.0fitbit

Accessing FitBit API via R (no web scraping)


Does anyone have a working R script to access the API? I see there is a webscraping package, but I'd prefer to use the official API if possible.

Everything I've got and research I've done to authenticate via oauth 1 or 2 seems broken using the httr package.

For oauth 2:

library(httr)
app = '<OAuth 2.0 Client ID>'
key <- '<Client (Consumer) Key>'
secret <- '<Client (Consumer) Secret>'
accessTokenURL <- 'https://api.fitbit.com/oauth2/token'
authorizeURL <- 'https://www.fitbit.com/oauth2/authorize'

fbr <- oauth_app(key,app,NULL)
fitbit <- oauth_endpoint(NULL, authorizeURL,accessTokenURL)
token <- oauth2.0_token(fitbit,fbr,scope='profile',as_header=TRUE, cache=FALSE)

When I check token$credentials I get the error message:

$errors
$errors[[1]]
$errors[[1]]$errorType
[1] "oauth"

$errors[[1]]$fieldName
[1] "n/a"

$errors[[1]]$message
[1] "No Authorization header provided in the request. Each call to Fitbit API should be OAuth signed"



$success
[1] FALSE

I have tried all the misc settings in fitbit setting up my app, both as a server and a client, and I have my callback URL correctly set up as http://localhost:1410

Any ideas?

Thanks, Isaac

ps: I've crossposted on fitbit's forums: https://twitter.com/IsaacWyatt/status/637768649290350592 and also tweeted at Hadley Wickham for help. Retweets welcome!

Current session info:
R version 3.1.2 (2014-10-31)
Platform: x86_64-apple-darwin13.4.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] httr_1.0.0

loaded via a namespace (and not attached):
[1] curl_0.9.3      httpuv_1.3.2    jsonlite_0.9.14 R6_2.0.1        Rcpp_0.11.4     stringr_0.6.2  
[7] tools_3.1.2    

Solution

  • So I asked for help on fitbit's forums as well, and user grahamrp posted the following using oauth 1.0:

    library(httr)
    token_url = 'https://api.fitbit.com/oauth/request_token'
    access_url = 'https://api.fitbit.com/oauth/access_token'
    auth_url = 'https://www.fitbit.com/oauth/authorize'
    key <- '<Client (Consumer) Key>'
    secret <- '<Client (Consumer) Secret>'
    
    myapp = oauth_app('data_access', key, secret)
    fb_ep = oauth_endpoint(token_url, auth_url, access_url)
    token = oauth1.0_token(fb_ep, myapp)
    gtoken = config(token = token)
    
    resp = GET('https://api.fitbit.com/1/user/-/sleep/date/today.json', gtoken)
    content(resp)
    

    This works for me as of 8/31/2015 Link: https://community.fitbit.com/t5/Web-API/Working-R-script-Using-API-R-Mac-OS-X/m-p/931586/highlight/false#M3002

    Thanks all for your attention to this!

    Best,

    Isaac