Fitbit API + JavaScript Web Tutorial with OAuth 2.0!

   Raja Tamil • Jul 23 • • 4 comments

In this Fitbit API + JavaScript Web tutorial, you will learn how your application can get various user data from Fitbit API using Client-side OAuth 2.0 authentication via AJAX to your JavaScript.

By the end of it, you will know how to get Fitbit use data like steps, heart rate etc to your application,

You should be comfortable with JavaScript and AJAX if not, check out in here

Let’s get into it right now! ⛷

I have split this article into FIVE parts,

  1. First, Understanding OAuth 2.0 and Implicit Grant Flow
  2. After that, Register an app in your Fitbit Developer Account
  3. Next, Getting user’s heart rate data from Fitbit API via AJAX
  4. Finally, you will learn how to Revoke OAuth 2.0 token from your application.

1. Fitbit OAuth 2.0 and Implicit Grant Flow

Why OAuth 2.0?: Because Fitbit uses OAuth 2.0 for handling user Authentication and Authorization.

So, What is OAuth 2.0?

OAuth 2.0 diagramfigure reference https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2

Like some other web applications that you may have seen that, in their signup process, they use “Login with Facebook” or “Login with Twitter” like so rather than giving a user a signup form to type username, password blah.. blah…

Those applications implement OAuth 2.0 for user authentication. Similarly, You are going to need a button says “Login with Fitbit” to access Fitbit Data.

So, OAuth 2.0 is a concepts/framework requires your application to obtain an access token when Fitbit users give permission to authenticate and authorize to access their own Fitbit data inside your app.

The way you do is, once you get an OAuth token, save it on the client-side, then use it whenever your app will need to make any additional HTTP request to Fitbit API for more user data.

If you want to know more about OAuth 2.0, you can check it detailed explanation here

Implicit Grant workflow: is one of the Fitbit OAuth 2.0 Application types. The other one is Authorization Code Grant Flow.

Implicit Grant workflow can be used to authenticate/authorize client-side applications via OAuth token, On the other hand, Authorization code Grant Flow can be used to authenticate/authorize client-side as well as server-side application.

I use Implicit Grant workflow as I will be using JavaScript to do client-side authentication.

I won’t be covering Authorization Code Grant Flow in the article. If you want to know more about it, check out the Fitbit API documentation.

2. Register a new app in your Fitbit Developer Account.

STEP #1: Login to Your Fitbit Account by going to https://dev.fitbit.com/login, If you do not have an account, you can create one going to https://www.fitbit.com/login

The good news is you do not need to have a Fitbit device in order to create an account.

However, I would recommend you to have Fitbit device so that you can track your own data to see what type of data Fitbit API sends to your application. I use Fitbit Alta HR and it works great!

Okay.

Once you have created an account, go to https://dev.fitbit.com/login page and click REGISTER AN APP tab.

Then, log in with your credential.

STEP #2: Fill the Register an Application Form

Application Name*: Your application name and this name will be shown to the users “Allow” permission page.

Description*: This could be the application description

Application Website*: This could be your application home name

Organization: This is your organization name which will appear on the Fitbit users authorization page.

You can go ahead fill Organization Website, Terms of Service and Privacy Policy URLs of your website.

Next, this is the most IMPORTANT one.

OAuth 2.0 Application Type: choose Client

Note: If there is any form validation error when you click Register button at the bottom, server option will be selected by default, so you will have to reselect the client option before click submit/register button again.

Next,

Callback URL: I am going to have my main page as a callback URL so in my case localhost/fitbit-api-javascript

What will happen is, when users authorize their Fitbit, it redirects to this callback URL (that you are adding into this field) with some additional parameters such as OAuth token, userid etc.

As I mentioned before, this OAuth token will be used to make any additional HTTP requests to the Fitbit API.

Default Access Type: I would set it to the Read-only mode for simplicity sake. If you want to use Read & Write, feel free comment below that I can help you with as it’s an outside scope of this topic.

3. Get Heart Rate User Data from Fitbit API.

STEP #1: Create a simple project and run it on the local server

Here is my folder structure.

fitbit-api-javascript
| index.html
| app.js

Here is my index.html file and it’s pretty staright forward

<!DOCTYPE html>
<html>

<head>
    <title>Fitbit API JavaScript</title>
</head>

<body>
    <script src="app.js"></script>
</body>

</html>

and the app.js file is empty.

STEP #2: Get the Login with Fitbit Link from Fitbit Developer Account.

  • Go to Manage My Apps → Select the Application you have registered →  click OAuth 2.0 tutorial page link.
  • [Screenshot attached]

STEP #3: create an <a> tag inside your index.html page and set copied URL as a value of the href attribute.

<a href="https://www.fitbit.com/oauth2/authorize?response_type=token&client_id=22CVMG&redirect_uri=https%3A%2F%2Flocalhost%2Ffitbit-api-javascript%2F&scope=activity%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight&expires_in=604800">
Login to Fitbit
</a>

That it’

Now you will be able to click the Login with Fitbit link which will take the user to authenticate/authorize Fitbit Account.

Once it’s authorized, you can see Fitbit redirects to the callback URL with some parameters such as OAuth token, User Id etc like below.

Here is the Fun part! 🙂

STEP #4: Extract OAuth Access Token and User id from the callback URL

I use split function in my app.js file to extract user id and OAuth token from the URL

// get the url 
var url = window.location.href;
//getting the access token from url 
var access_token = url.split("#")[1].split("=")[1].split("&")[0]; 
// get the userid 
var userId = url.split("#")[1].split("=")[2].split("&")[0]; 
console.log(access_token); 
console.log(userId);

Now, you got that information out of the way…

STEP #5: Get a resource URL for heart rate time series data

Next thing you need is resource URL for Heart Rate Data. You can find resource URLs for different categories in the Fitbit API Documentation here

Fitbit provides two resource URLs for getting time series heart rate data.

Here is the first one.

https://api.fitbit.com/1/user/[user-id]/activities/heart/date/[date]/[period].json

You would need to fill a few parameters that are in the square bracket in the resource URL when making a request.

user-id: we have already got it from the call back URL in the previous steps.
date: This parameter represents the end date in the format of yyyy-MM-dd or you can use today
period: The range for which data will be returned. Options are 1d, 7d, 30d, 1w, 1m.

So, if you want data past a week data until today, your resource url would look like this.
https://api.fitbit.com/1/user/5YW8G8/activities/heart/date/today/1w.json

STEP #5: Make an AJAX HTTP request to Fitbit API Resource Server

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.fitbit.com/1/user/' + userId + '/activities/heart/date/today/1w.json');
xhr.setRequestHeader("Authorization", 'Bearer ' + access_token);
xhr.onload = function () {
    if (xhr.status === 200) {
        console.log(xhr.responseText)
    }
};
xhr.send()

As you can see the above code, I have created an HTTP request Object to make a request to Fitbit API.

Then invoking the open method on it and passing two arguments,

  • Request method GET and
  • Resource URL for heart rate with required param values.

After that, I set Authorization request Header (based on OAuth 2.0 protocol) by concatenating the keyword Bearer with the access_token (OAuth token) that I have got it from the callback URL earlier.

If everything goes well, you should get the response back inside the onload function that I have console logged on the browser.

{
    "activities-heart": [{
        "dateTime": "2018-03-25",
        "value": {
            "customHeartRateZones": [],
            "heartRateZones": [{
                "caloriesOut": 667.27228,
                "max": 87,
                "min": 30,
                "minutes": 540,
                "name": "Out of Range"
            }, {
                "caloriesOut": 1706.79212,
                "max": 122,
                "min": 87,
                "minutes": 823,
                "name": "Fat Burn"
            }, {
                "caloriesOut": 112.48714,
                "max": 148,
                "min": 122,
                "minutes": 15,
                "name": "Cardio"
            }, {
                "caloriesOut": 12.43216,
                "max": 220,
                "min": 148,
                "minutes": 1,
                "name": "Peak"
            }],
            "restingHeartRate": 83
        }
    }, {
        "dateTime": "2018-03-31",
        "value": {
            "customHeartRateZones": [],
            "heartRateZones": [{
                "caloriesOut": 575.94372,
                "max": 87,
                "min": 30,
                "minutes": 465,
                "name": "Out of Range"
            }, {
                "caloriesOut": 931.33614,
                "max": 122,
                "min": 87,
                "minutes": 490,
                "name": "Fat Burn"
            }, {
                "caloriesOut": 105.67336,
                "max": 148,
                "min": 122,
                "minutes": 13,
                "name": "Cardio"
            }, {
                "caloriesOut": 0,
                "max": 220,
                "min": 148,
                "minutes": 0,
                "name": "Peak"
            }],
            "restingHeartRate": 84
        }...
    }]
}

Now, heart rate data inside your application, so you can present however you want.

Nice. 🙂

Here is an another resource url for heart rate if you want just use the start and end date instead of period like the one I just showed.

https://api.fitbit.com/1/user/[user-id]/activities/heart/date/[base-date]/[end-date].json

base-date: The range start date, in the format yyyy-MM-dd or today.

end-date: The end date of the range.

Sweet!

Here is another one

Fitbit API – Get Steps

Similar to Heart Rate, you can use two different ways to get the users steps data

https://api.fitbit.com/1/user/[userId/activities/steps/date/today/1w.json
https://api.fitbit.com/1/user/[userId]/activities/steps/date/[base-date]/[end-date].json

For other activities like Sleep, Body Weight, Food Logging, Distance etc.

Check out Fitbit API documentation https://dev.fitbit.com/build/reference/web-api/activity/

4. Revoke access from Fitbit API Authorization Server

Step #1: Add Revoke Access button to the index.html and add the inline javascript function called revokeAccess() to it.

<button onclick="revokeAccess()">revokeAccess</button>

Step #2: create the revokeAccess() function inside app.js like below in which you add the AJAX POST for revoking access from Fitbit API Authorization Server.

function revokeAccess() {
    var params = "token=" + access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://api.fitbit.com/oauth2/revoke');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Authorization", 'Basic MjJDVk1HOjcyZTAwMjhkNTcyM2MxYzYyZTU3OWE4ZTQ3MDUyOTFm', true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            console.log(xhr.responseText)
        }
    };
    xhr.send(params);
}

I have created xhr HTTP Request object similar to previous one.

This time HTTP method is POST instead of GET with the revoke resource URL https://api.fitbit.com/oauth2/revoke

After that, I specified what type of content I am sending with this POST HTTP request on the header, in this case, form-urlencoded as a Content-Type.

Another important thing you need set in the header is base 64 STRING after the word Basic.

Base 64 is a type of encoding binary data. You can check it out more about it at StackOverflow for the better explanation.

Step #3: create the base64 encoded string

  • Login to your Fitbit Developer Account → Go to Manage My Apps Tab
  • Choose the app you’re working on copy OAuth 2.0 Client ID and Client Secret ID
  • Combine together with : between, for example 22FVDG:72e0028d5723c1c62e579a8e4705291f
  • Then, Go to  https://www.base64encode.org
  • Paste the string and click encode

Copy the encoded string and paste it (xhr.setRequestHeader(“Authorization”, ‘Basic BASE64STRINGHERE, true);

What kind of app are you building with Fitbit API and Are you using Client-side or Server-side Authorization?

Sharing is caring!