Integrate Google Fit in ASP.NET Core Web API

Author: Dasan | Date: April 11, 2025

1. 🧠 Introduction

Google Fit provides access to fitness data including steps, calories, heart rate, and more. In this blog, you'll learn how to access Google Fit data from an ASP.NET Core Web API using OAuth2 authentication and REST calls.

2. βš™οΈ Prerequisites

3. πŸ” Register OAuth2 Credentials

  1. Go to Google Cloud Console
  2. Enable Fitness API
  3. Create OAuth 2.0 Client ID credentials
  4. Set the redirect URI (e.g. https://yourdomain.com/oauth2callback)
  5. Save Client ID & Client Secret

4. βœ… Required Scopes

https://www.googleapis.com/auth/fitness.activity.read
https://www.googleapis.com/auth/fitness.body.read
https://www.googleapis.com/auth/fitness.location.read

5. πŸ› οΈ Redirect to Google for Authorization

public IActionResult GoogleFitLogin()
{
    var clientId = "YOUR_CLIENT_ID";
    var redirectUri = "https://yourdomain.com/oauth2callback";
    var scopes = "https://www.googleapis.com/auth/fitness.activity.read";

    var authUrl = $"https://accounts.google.com/o/oauth2/v2/auth?response_type=code" +
                  $"&client_id={clientId}&redirect_uri={redirectUri}&scope={scopes}&access_type=offline";

    return Redirect(authUrl);
}

6. πŸ” Exchange Code for Access Token

public async Task<string> ExchangeCodeAsync(string code)
{
    var client = new HttpClient();
    var dict = new Dictionary<string, string>
    {
        { "code", code },
        { "client_id", "YOUR_CLIENT_ID" },
        { "client_secret", "YOUR_CLIENT_SECRET" },
        { "redirect_uri", "https://yourdomain.com/oauth2callback" },
        { "grant_type", "authorization_code" }
    };

    var response = await client.PostAsync("https://oauth2.googleapis.com/token", new FormUrlEncodedContent(dict));
    var content = await response.Content.ReadAsStringAsync();
    var token = JsonSerializer.Deserialize<OAuthToken>(content);
    return token.AccessToken;
}

7. 🧾 Call Google Fit API (Example: Steps Count)

public async Task<string> GetStepCountAsync(string accessToken)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    var requestBody = new
    {
        aggregateBy = new[] {
            new { dataTypeName = "com.google.step_count.delta" }
        },
        bucketByTime = new { durationMillis = 86400000 }, // 1 day
        startTimeMillis = DateTimeOffset.UtcNow.AddDays(-1).ToUnixTimeMilliseconds(),
        endTimeMillis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
    };

    var json = JsonSerializer.Serialize(requestBody);
    var content = new StringContent(json, Encoding.UTF8, "application/json");

    var response = await client.PostAsync("https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate", content);
    return await response.Content.ReadAsStringAsync();
}

8. πŸ“¦ Create Token Model

public class OAuthToken
{
    [JsonPropertyName("access_token")]
    public string AccessToken { get; set; }

    [JsonPropertyName("refresh_token")]
    public string RefreshToken { get; set; }

    [JsonPropertyName("expires_in")]
    public int ExpiresIn { get; set; }
}

9. πŸ§ͺ Testing and Validation

10. πŸ” Secure and Refresh Access Tokens

Access tokens expire quickly. Use the refresh_token to get a new access token when needed using the same token endpoint with grant_type=refresh_token.

11. 🏁 Conclusion

Google Fit integration with ASP.NET Core Web API allows you to sync and analyze users’ health and fitness data. Whether you're building a wellness tracker or a smart health dashboard, this integration opens up powerful capabilities.

In the next blog, we'll go over integrating Health Connect for Android to sync data bi-directionally with Google Fit. Stay tuned! πŸ’ͺ