Overview

Google Fitness REST APIs are useful if you have a fitness app and you want to integrate your data with Google Fit or if you just want to collect the fitness data and display some information to the users. The Google Fit REST APIs can be consumed in SharePoint Framework.
In this article, we will explore how we can use Google Fit REST APIs in SPFx web part and develop a web part to display the key fitness information from the Google Fit data source. We will use React JS in this example. For this article, I am using SharePoint Framework version 1.7.1

Create SPFx Solution

Open the command prompt. Create a directory for SPFx solution.
  1. md react-google-fit
Navigate to the above-created directory.
  1. cd react-google-fit
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint
Yeoman generator will present you with the wizard by asking questions about the solution to be created.
SharePoint Framework - Display Google Fit Information
Solution Name: Hit Enter to have a default name (react-google-fit in this case) or type in any other name for your solution.
Selected choice: Hit Enter
Target for component: Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
Place of files: We may choose to use the current folder or create a subfolder for our solution.
Selected choice: Use the current folder
Deployment option: We may choose to allow the tenant admin the choice of being able to deploy the solution to all sites immediately without running any feature deployment or adding apps in sites.
Selected choice: N (install on each site explicitly)
Type of client-side component to create: We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice: WebPart
Web part name: Hit Enter to select the default name or type in any other name.
Selected choice: GoogleFitActivityViewer
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Display Google Fit Activities
Framework to use: Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice: React
Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command.
  1. npm shrinkwrap
In the command prompt, type the below command to open the solution in a code editor of your choice.
  1. code .

NPM Packages Used

react-google-authorize (https://www.npmjs.com/package/react-google-authorize)
This npm package helps to authenticate and authorize to Google.
Open “\src\webparts\googleFitActivityViewer\components\GoogleFitActivityViewer.tsx”.
Include the package.
  1. import { GoogleAuthorize } from 'react-google-authorize';
Use the GoogleAuthorize component in render method.
  1. public render(): React.ReactElement<IGoogleFitActivityViewerProps> {
  2. const responseGoogle = (response) => {
  3. }
  4. return (
  5. <div className={styles.googleFitActivityViewer}>
  6. <div className={styles.container}>
  7. {
  8. !this.state.isGoogleAuthenticated && this.state.accessToken == "" &&
  9. <GoogleAuthorize
  10. scope={'https://www.googleapis.com/auth/fitness.activity.read https://www.googleapis.com/auth/fitness.location.read'}
  11. clientId={this.props.clientId}
  12. onSuccess={responseGoogle}
  13. onFailure={responseGoogle}
  14. >
  15. <span>Login with Google</span>
  16. </GoogleAuthorize>
  17. }
  18. </div>
  19. </div>
  20. );
  21. }
We are including the below scopes.
  • https://www.googleapis.com/auth/fitness.activity.read - To read the fitness activities (calories burned, step count)
  • https://www.googleapis.com/auth/fitness.location.read - To read activity time spent, distance travelled

Define State

Create a new file IGoogleFitActivityViewerState.ts under “\src\webparts\googleFitActivityViewer\components\” folder.
  1. export interface IGoogleFitActivityViewerState {
  2. isGoogleAuthenticated: boolean;
  3. accessToken: string;
  4. stepCount: number;
  5. calories: number;
  6. distance: number;
  7. activityTime: number;
  8. }
2. Update your component “\src\webparts\googleFitActivityViewer\components\ GoogleFitActivityViewer.tsx” to use the state.
  1. import { IGoogleFitActivityViewerState } from './IGoogleFitActivityViewerState';
  2. export default class GoogleFitActivityViewer extends React.Component<IGoogleFitActivityViewerProps, IGoogleFitActivityViewerState> {
  3. public constructor(props) {
  4. super(props);
  5. this.state = {
  6. isGoogleAuthenticated: false,
  7. accessToken: "",
  8. stepCount: 0,
  9. calories: 0,
  10. distance: 0,
  11. activityTime: 0
  12. };
  13. }
  14. }

Implement the Service

We will create a service to query Google Fit REST APIs.

Interface to represent REST API data

Let us define an interface to represent the data returned by REST APIs.
Create a folder “services” under “src” folder and add a file IFitnessActivity.ts.
  1. export interface IFitnessActivity {
  2. dataSourceId: string;
  3. maxEndTimeNs: string;
  4. minStartTimeNs: string;
  5. point: IFitnessPoint[];
  6. }
  7. export interface IFitnessPoint {
  8. dataTypeName: string;
  9. endTimeNanos: string;
  10. modifiedTimeMillis: string;
  11. value: IFitnessPointValue[];
  12. }
  13. export interface IFitnessPointValue {
  14. intVal: number;
  15. fpVal: number;
  16. }
Implement Generic Interface
Add a file IDataService.ts under “\src\services” folder.
  1. export interface IDataService {
  2. getStepCount: (accessToken: string) => Promise<any>;
  3. getCalories: (accessToken: string) => Promise<any>;
  4. getDistance: (accessToken: string) => Promise<any>;
  5. getActivityTime: (accessToken: string) => Promise<any>;
  6. }
Implement Google Fit Interface
Add a file GoogleFitService.ts under “\src\services” folder implementing IDataService interface.
  1. import { ServiceScope, ServiceKey } from "@microsoft/sp-core-library";
  2. import { IDataService } from './IDataService';
  3. import { HttpClient, HttpClientResponse, IHttpClientOptions } from '@microsoft/sp-http';
  4. import { PageContext } from '@microsoft/sp-page-context';
  5. import { IFitnessActivity, IFitnessPoint, IFitnessPointValue } from './IFitnessActivity';
  6. export class GoogleFitService implements IDataService {
  7. public static readonly serviceKey: ServiceKey<IDataService> = ServiceKey.create<IDataService>('googleFit:data-service', GoogleFitService);
  8. private _httpClient: HttpClient;
  9. private _pageContext: PageContext;
  10. constructor(serviceScope: ServiceScope) {
  11. serviceScope.whenFinished(() => {
  12. // Configure the required dependencies
  13. this._httpClient = serviceScope.consume(HttpClient.serviceKey);
  14. this._pageContext = serviceScope.consume(PageContext.serviceKey);
  15. });
  16. }
  17. // Get step count from Google fit data source
  18. public getStepCount(accessToken: string): Promise<number> {
  19. return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
  20. this.getGoogleFitData('derived:com.google.step_count.delta:com.google.android.gms:estimated_steps', accessToken)
  21. .then((fitnessData: IFitnessActivity): void => {
  22. var stepsCount: number = 0;
  23. var i: number = 0;
  24. var j: number = 0;
  25. // Calculate step count of each activity
  26. for (i = 0; i < fitnessData.point.length; i++) {
  27. for (j = 0; j < fitnessData.point[i].value.length; j++) {
  28. stepsCount += fitnessData.point[i].value[j].intVal;
  29. }
  30. }
  31. resolve(stepsCount);
  32. });
  33. });
  34. }
  35. // Get calories burned from Google fit data source
  36. public getCalories(accessToken: string): Promise<number> {
  37. return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
  38. this.getGoogleFitData('derived:com.google.calories.expended:com.google.android.gms:merge_calories_expended', accessToken)
  39. .then((fitnessData: IFitnessActivity): void => {
  40. var calories: number = 0;
  41. var i: number = 0;
  42. var j: number = 0;
  43. // Calculate calories burned during each activity
  44. for (i = 0; i < fitnessData.point.length; i++) {
  45. for (j = 0; j < fitnessData.point[i].value.length; j++) {
  46. calories += fitnessData.point[i].value[j].fpVal;
  47. }
  48. }
  49. resolve(calories);
  50. });
  51. });
  52. }
  53. // Get distance travelled from Google fit data source
  54. public getDistance(accessToken: string): Promise<number> {
  55. return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
  56. this.getGoogleFitData('derived:com.google.distance.delta:com.google.android.gms:merge_distance_delta', accessToken)
  57. .then((fitnessData: IFitnessActivity): void => {
  58. var distance: number = 0;
  59. var i: number = 0;
  60. var j: number = 0;
  61. // Calculate distance travelled during each activity
  62. for (i = 0; i < fitnessData.point.length; i++) {
  63. for (j = 0; j < fitnessData.point[i].value.length; j++) {
  64. distance += fitnessData.point[i].value[j].fpVal;
  65. }
  66. }
  67. resolve(distance / 1000);
  68. });
  69. });
  70. }
  71. // Get activity time from Google fit data source
  72. public getActivityTime(accessToken: string): Promise<number> {
  73. return new Promise<number>((resolve: (itemId: number) => void, reject: (error: any) => void): void => {
  74. this.getGoogleFitData('derived:com.google.activity.segment:com.google.android.gms:merge_activity_segments', accessToken)
  75. .then((fitnessData: IFitnessActivity): void => {
  76. var activityTime: number = 0;
  77. var i: number = 0;
  78. var j: number = 0;
  79. // Calculate activity time spent for each activity
  80. for (i = 0; i < fitnessData.point.length; i++) {
  81. for (j = 0; j < fitnessData.point[i].value.length; j++) {
  82. activityTime += fitnessData.point[i].value[j].intVal;
  83. }
  84. }
  85. resolve(activityTime);
  86. });
  87. });
  88. }
  89. // Get Google fit data by calling the REST API
  90. private getGoogleFitData(activityScope: string, accessToken: string): Promise<IFitnessActivity> {
  91. // Calculate start date, end date
  92. var startTime: number = new Date().getTime();
  93. var todayMidnight: Date = new Date();
  94. todayMidnight.setHours(0, 0, 0, 0);
  95. var endTime: number = todayMidnight.getTime();
  96. const requestHeaders: Headers = new Headers();
  97. requestHeaders.append("Content-type", "application/json");
  98. requestHeaders.append("Cache-Control", "no-cache");
  99. const postOptions: IHttpClientOptions = {
  100. headers: requestHeaders
  101. };
  102. let sessionUrl: string = `https://www.googleapis.com/fitness/v1/users/me/dataSources/` + activityScope + `/datasets/` + startTime + `000000-` + endTime + `000000?access_token=` + accessToken;
  103. return new Promise<IFitnessActivity>((resolve: (itemId: IFitnessActivity) => void, reject: (error: any) => void): void => {
  104. this._httpClient.get(sessionUrl, HttpClient.configurations.v1, postOptions)
  105. .then((response: HttpClientResponse) => {
  106. response.json().then((responseJSON: IFitnessActivity) => {
  107. resolve(responseJSON);
  108. });
  109. });
  110. });
  111. }
  112. }
Code the WebPart
Open the web part named GoogleFitActivityViewer.tsx under the “\src\webparts\googleFitActivityViewer\components\” folder. Here, implement the render method.
  1. public render(): React.ReactElement<IGoogleFitActivityViewerProps> {
  2. const responseGoogle = (response) => {
  3. this.setState(() => {
  4. return {
  5. ...this.state,
  6. isGoogleAuthenticated: true,
  7. accessToken: response.access_token
  8. };
  9. });
  10. this.readStepCount(this.state.accessToken);
  11. this.readCalories(this.state.accessToken);
  12. this.readDistance(this.state.accessToken);
  13. this.readActivityTime(this.state.accessToken);
  14. };
  15. const formatNumber = (num) => parseFloat(num.toFixed(2)).toLocaleString().replace(/\.([0-9])$/, ".$10");
  16. return (
  17. <div className={styles.googleFitActivityViewer}>
  18. <div className={styles.container}>
  19. {
  20. !this.state.isGoogleAuthenticated && this.state.accessToken == "" &&
  21. <GoogleAuthorize
  22. scope={'https://www.googleapis.com/auth/fitness.activity.read https://www.googleapis.com/auth/fitness.location.read'}
  23. clientId={this.props.clientId}
  24. onSuccess={responseGoogle}
  25. onFailure={responseGoogle}
  26. >
  27. <span>Login with Google</span>
  28. </GoogleAuthorize>
  29. }
  30. {
  31. this.state.isGoogleAuthenticated &&
  32. <div>
  33. <div className={styles.msTable}>
  34. <div className={styles.msTableRowHeader}>
  35. <span className={styles.msTableCell}>
  36. Today, {new Date().toDateString()}
  37. </span>
  38. </div>
  39. </div>
  40. <div className={styles.msTable}>
  41. <div className={styles.msTableRow}>
  42. <span className={styles.msTableCell}>
  43. <Icon iconName="Clock" className="ms-IconExample" />
  44. </span>
  45. <span className={styles.msTableCell}>
  46. <b>{formatNumber(this.state.activityTime)}</b> min
  47. </span>
  48. </div>
  49. <div className={styles.msTableRow}>
  50. <span className={styles.msTableCell}>
  51. <Icon iconName="POI" className="ms-IconExample" />
  52. </span>
  53. <span className={styles.msTableCell}>
  54. <b>{formatNumber(this.state.distance)}</b> km
  55. </span>
  56. </div>
  57. <div className={styles.msTableRow}>
  58. <span className={styles.msTableCell}>
  59. <Icon iconName="CaloriesAdd" className="ms-IconExample" />
  60. </span>
  61. <span className={styles.msTableCell}>
  62. <b>{formatNumber(this.state.calories)}</b> calories
  63. </span>
  64. </div>
  65. <div className={styles.msTableRow}>
  66. <span className={styles.msTableCell}>
  67. <Icon iconName="Running" className="ms-IconExample" />
  68. </span>
  69. <span className={styles.msTableCell}>
  70. <b>{formatNumber(this.state.stepCount)}</b> steps
  71. </span>
  72. </div>
  73. </div>
  74. </div>
  75. }
  76. </div>
  77. </div>
  78. );
  79. }
Implement the helper methods and set the states from it.
  1. private readStepCount(accessToken: string): void {
  2. let serviceScope: ServiceScope = this.props.serviceScope;
  3. this.dataCenterServiceInstance = serviceScope.consume(GoogleFitService.serviceKey);
  4. this.dataCenterServiceInstance.getStepCount(accessToken).then((stepCount: number) => {
  5. this.setState(() => {
  6. return {
  7. ...this.state,
  8. stepCount: stepCount
  9. };
  10. });
  11. });
  12. }
  13. private readCalories(accessToken: string): void {
  14. let serviceScope: ServiceScope = this.props.serviceScope;
  15. this.dataCenterServiceInstance = serviceScope.consume(GoogleFitService.serviceKey);
  16. this.dataCenterServiceInstance.getCalories(accessToken).then((calories: number) => {
  17. this.setState(() => {
  18. return {
  19. ...this.state,
  20. calories: calories
  21. };
  22. });
  23. });
  24. }
  25. private readDistance(accessToken: string): void {
  26. let serviceScope: ServiceScope = this.props.serviceScope;
  27. this.dataCenterServiceInstance = serviceScope.consume(GoogleFitService.serviceKey);
  28. this.dataCenterServiceInstance.getDistance(accessToken).then((distance: number) => {
  29. this.setState(() => {
  30. return {
  31. ...this.state,
  32. distance: distance
  33. };
  34. });
  35. });
  36. }
  37. private readActivityTime(accessToken: string): void {
  38. let serviceScope: ServiceScope = this.props.serviceScope;
  39. this.dataCenterServiceInstance = serviceScope.consume(GoogleFitService.serviceKey);
  40. this.dataCenterServiceInstance.getActivityTime(accessToken).then((activityTime: number) => {
  41. this.setState(() => {
  42. return {
  43. ...this.state,
  44. activityTime: activityTime
  45. };
  46. });
  47. });
  48. }

Add Authorized JavaScript Origins

Please refer to my previous article to generate OAuth 2.0 client ID.
  1. Open Google Developer Dashboard from here.
  2. Select the project created by following instructions from the previous article.
  3. From left navigation, click "Credentials".
  4. Click the listed web client.

    SharePoint Framework - Display Google Fit Information

  5. Under Authorized JavaScript origins, add SharePoint Online site URL (e.g. https://contoso.sharepoint.com ) or https://localhost:4321 if you are using SharePoint local workbench.

  6. Under Authorized redirect URI, add https://localhost:4321/auth/google/callback, if you are using SharePoint local workbench.

    SharePoint Framework - Display Google Fit Information

  7. Click "Save".

Configure the Web Part to use

  1. Add "Google Fit Activity Viewer" web part on the SharePoint page.
  2. Edit the web part.
  3. Add the above generated OAuth 2.0 client ID to "ClientId Field" web part property.
  4. Save the changes.

    SharePoint Framework - Display Google Fit Information

Summary

Google Fit REST APIs can be consumed in SharePoint Framework web part to display the key fitness information (activity time spent, distance traveled, calories burned, step count) from the Google fit data source. Npm package (react-google-authorize) helps in authenticating and authorizing the scopes in Google.