Author: Dasan | Date: April 11, 2025
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.
Fitness APIhttps://yourdomain.com/oauth2callback)https://www.googleapis.com/auth/fitness.activity.read
https://www.googleapis.com/auth/fitness.body.read
https://www.googleapis.com/auth/fitness.location.read
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);
}
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;
}
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();
}
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; }
}
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.
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! πͺ