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 user data like steps, heart rate etc. to your application.

You should be comfortable with JavaScript and AJAX, if not, check out the blog here.

Let’s get into it right now! ⛷

I have split this article into FOUR parts,

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

So, What is OAuth 2.0?

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

Like some other web applications that you may have seen, 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 that says “Login with Fitbit” to access Fitbit Data.

So, OAuth 2.0 is a concepts/framework that 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 this 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 the 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 this article. If you want to know more about it, check out the Fitbit API documentation.

STEP #1: Log in to Your Fitbit Account by going to https://dev.fitbit.com/login, If you do not have an account, you can create one by 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 that you to have a 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 the https://dev.fitbit.com/login page and click REGISTER AN APP tab.

Then, log in with your credentials.

STEP #2: Fill the Register an Application Form

Application Name*: Your application name, 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 and fill in the 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 you click the 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 to comment below and I can help you with it there as it’s outside the scope of this topic.

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 straight 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 the Fitbit Developer Account.

Go to Manage My Apps → Select the Application you have registered → click OAuth 2.0 tutorial page link .

Select the you have registered click 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’s 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 the 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 the 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 will need to fill in a few parameters that are in the square bracket in the resource URL when making a request.

user-id: We 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 for the past week until today, your resource url would look like this:

https://api.fitbit.com/1/user/5YW8G8/activities/heart/date/today/1w.json

STEP #6: 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 in 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

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 got 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, the heart rate data is inside your application, so you can present it however you want.

Nice. 🙂

Here is another resource url for heart rate if you want it, just use the start and end date instead of the 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 user’s 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 the Fitbit API documentation. https://dev.fitbit.com/build/reference/web-api/activity/

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 the 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 out more about it at StackOverflow for a better explanation.

Step #3: Create the base64 encoded string

Log in to your Fitbit Developer Account → Go to Manage My Apps Tab

Go to Tab Choose the app you’re working on → copy OAuth 2.0 Client ID and Client Secret ID

copy and Combine together with : between, for example 22FVDG:72e0028d5723c1c62e579a8e4705291f

Then, Go to → https://www.base64encode.org

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?