I think Google Fit is a wonderful platform. It connects multiple devices and apps to give you insight into your fitness. I connected a Withing Smart Body Analyzer scale to the system. What I’m missing is a simple min / max weight per day graph, something like this:Google Fit Graph

This blog describes how to get the weight data out of Google Fit into your C# application. You can use your own chats solution to plot a graph like this.

1. Google Fit Nuget Package

Google was kind enough to create a C# wrapper around the Google Fit API and provided a Nuget package for us:

Install-Package Google.Apis.Fitness.v1»

2. Scope, credentials + service

Next you’ll need to get your credentials ready. How you do this is outside the scope of this tutorial as it depends on what platform you use. The credential needs to be created with scope FitnessService.Scope.FitnessBodyRead. The FitnessService needs a UserCredential. I’ve implemented the Google MVC Authentication flow that will give met a result that provides a credential:

You can read more on Offline Google Authentication for MVC.Net here.

3. Base class for querying

Google Fit works with data sets that can be queried using a DataSourceId and a DataSourceType. The query mechanism will seem somewhat weird at first as it uses a myriad of objects. To make things easier, I’ve created an abstract FitnessQuery class. It facilitates the creation and execution of the queries on the data sets.

To make handling of time easier I’ve created the GoogleTime class – it is appended at the end of the article.

4. Querying weight

Next I created the WeightQuery class. It will query data source derived:com.google.weight:com.google.android.gms:merge_weight using data type com.google.body..

I use LINQ to query the content of the response and convert it to a WeightDataPoint object. The QueryWeight(…) method returns a list with all the data points. The QueryWeightPerDay(…) will also return a list, but it will return a unique data point per day with a max and a min weight. Only the data part of the stamp will be used in this method.

5. Mixing it together in a data table

I’m using Google Charts to plot the graph. It uses a data table – basically jagged array. Again I’ll use LINQ to create the array.

This dataTable can be serialized to JSON and used to create a Google Chart.

Handling time

The Google API uses milliseconds and nanoseconds. In C# I like to work with simple DateTime structures, that why I created the GoogleTime class that helps with the conversion between the two formats:

Final thoughts

Querying Google Fit using data sets, sources and types might seem difficult – but it is doable using Nuget and the documentation. Hopefully they’ll make it easier.