Access to the Google Health API is provided through
Google Cloud. To enable the API and authorize a Google Account, you'll
need a Google Cloud project.

*Whether you are an existing Fitbit API developer, or new to the Google Health
API, you'll need to complete this step in order to make calls to the API.*

## Create a project and an OAuth client

Use the **Enable the API and get an OAuth 2.0 Client ID** button to enable
the **Google Health API** and get an OAuth 2.0 Client ID:

1. If you have an existing Google Cloud project project that you would like to use for the Google Health API, make sure you are logged into the administrator account for that project first. Then select the existing project from the list of available projects after clicking the button. Otherwise, create a new project.
2. Select **Web Server** when it asks "Where are you calling from?".
3. Enter *https://www.google.com* as the value for **Authorized redirect
   URIs**. A redirect URI is required to obtain an Authorization Code using OAuth 2.0.
4. Once setup is complete, **copy the OAuth 2.0 Client ID and Client Secret
   values, and download the Credentials JSON to your local machine**.

Enable the API and get an OAuth 2.0 Client ID

If you want to manually set up your Google Cloud project, or verify
the setup and retrieve your credentials again:

1. Enable **Google Health API** on the [API Enablement](https://console.developers.google.com/apis/library/health.googleapis.com) page.
2. Get an OAuth 2.0 Client ID on the [Credentials](https://console.developers.google.com/apis/credentials) page.

For more information on setting up OAuth 2.0 using the Google console, see
[Using OAuth 2.0 to Access Google APIs](https://developers.google.com/identity/protocols/oauth2).

### Use separate projects for staging and production

The Google Health API doesn't provide a separate sandbox or staging
environment. All of your environments call the production Google Health API, so
you manage environment separation at the Google Cloud project level.

When setting up environments for your app, follow these best practices:

- Create separate Google Cloud projects for your development, staging, and production environments. Each project manages its own OAuth 2.0 client, consent screen, and webhook subscribers.
- Don't use your production Google Cloud project or its OAuth 2.0 client for testing, because changes to that project directly affect your production app.
- Develop and test in a non-production project first, and then apply your changes to your production project when ready.
- Use tags in the Google Cloud console to visually distinguish your projects by environment. For instructions, see [Designate project environments with
  tags](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects#designate_project_environments_with_tags).

### Add test users

By default, newly created OAuth clients are in an unverified state with a cap of
100 users for both testing and production purposes. To enable authorization
during this period, you must manually add each user's email address to the Test
users list in your project configuration.

Update the list of test users on the
[Audience](https://console.developers.google.com/auth/audience)
page:

1. On this page, you should see the "Publishing status" set to **Testing** , and the "User type" set to **External**.
2. Under the section "Test users", click **+ Add users**. Enter the email address for any test users that should be allowed to grant your app permission to access their health data.
3. Click **Save**.

Supporting more than 100 users with the Google Health API requires completion of
a third party security review. Additional information can be found in the [OAuth
App Verification Help Center](https://support.google.com/cloud/answer/13463073).

### Monitor OAuth token grant rate limits

Google Cloud enforces a rate limit on OAuth token grants to control how quickly your app can onboard or re-authenticate users. If you expect to exceed 10,000 user sign-ups or re-authentications within a 24-hour sliding window, request a higher quota in advance. For more information, see [OAuth application rate limits](https://support.google.com/cloud/answer/9028764).

### Add scopes

You must specify the scopes your client is allowed to call on the
[Data Access](https://console.developers.google.com/auth/scopes)
page:

1. On this page, click **Add or remove scopes**.
2. In the API column, search for "Google Health API". Select the scopes you need for your application.
3. After selecting all the scopes you need, click **Update** to return to the Data Access page.
4. Click **Save**.

Before selecting your scopes, review the
[scope implementation](https://developers.google.com/health/scopes#implementation).

You have finished setting up your client ID and should now be able to make calls
to the Google Health API.

### Update scopes

You can prompt the user to re-authorize your app by setting the prompt parameter
to consent in your authentication request. When `prompt=consent` is included,
the consent screen is displayed every time your app requests authorization of
scopes of access, even if all scopes were previously granted to your Google APIs
project.

To add or change scopes using the `prompt=consent` parameter, follow these
steps:

1. Identify the complete list of
   [Scopes](https://developers.google.com/health/scopes) your application
   needs. This should include both the existing scopes and any new ones you
   need to add.

2. Modify the scope parameter in the authorization URL to include the updated
   list of space-separated scope values.

3. Append `prompt=consent` to your authentication URI parameters. This forces
   the authorization server to prompt the user for consent before returning
   information to your client.

   The following example shows an HTTPS GET request to Google's OAuth 2.0
   authorization endpoint requesting multiple scopes with `prompt=consent`
   appended:

   ```
   https://accounts.google.com/o/oauth2/v2/auth?client_id=client-id&redirect_uri=redirect-uri&response_type=code&access_type=offline&scope=https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly%20https://www.googleapis.com/auth/googlehealth.sleep.readonly&prompt=consent
   ```
4. When the user follows the updated link, they will be presented with a
   consent page listing all requested scopes. Once the user clicks "Continue"
   or "Allow," you will receive a new authorization code that can be exchanged
   for tokens covering the full set of scopes.

   Include `prompt=consent` only when necessary, such as when you need to
   obtain a new refresh token or when the requested scopes have changed.

## OAuth2 client libraries

The list of available OAuth2 client libraries used to integrate with popular
frameworks can be found at
[Using OAuth 2.0 to Access Google APIs](https://developers.google.com/identity/protocols/oauth2#libraries).

When implementing Google OAuth in mobile or desktop apps, always use system
browsers (such as **Chrome Custom Tabs** on Android or
**ASWebAuthenticationSession** on iOS) and never use embedded WebViews, which
block passkeys and break Google OAuth flows. Review the
[Sign in with Google best practices](https://developers.google.com/identity/siwg/best-practices) for
guidance.

## Link Google Health before OAuth consent

Before a user goes through the Google OAuth 2.0 consent flow in your app, they
must sign in to the Google Health mobile app to link Google Health to their
Google Account. Google OAuth 2.0 authenticates any valid Google Account and
cannot check whether the account has an active Google Health profile during the
consent screen.

Instruct users to complete the following steps in the Google Health mobile app
before starting the OAuth consent flow in your app:

1. Download and open the Google Health mobile app from the Google Play Store or Apple App Store.
2. Tap **Sign in with Google** and select the Google Account they want to connect to your app.
3. Follow the in-app prompts to create a new Google Health profile, or follow the [Fitbit account migration steps](https://support.google.com/fitbit/answer/14237024) to move an existing Fitbit account to their Google Account.

After exchanging the authorization code for OAuth tokens, call the
[`users.getIdentity`](https://developers.google.com/health/endpoints#get-user-id) endpoint (`GET
https://health.googleapis.com/v4/users/me/identity`) to verify that the user's
Google Account is linked to Google Health before marking the account as
connected in your app. For details on handling unlinked accounts (`400`
`ACCOUNT_NOT_LINKED`), see
[Handle unlinked Google Accounts](https://developers.google.com/health/troubleshooting#412-precondition-failed).

## Refresh tokens

To maintain long-term access to Google APIs without requiring constant
user re-authentication, your application must use a refresh token. For
comprehensive implementation details, including the specific HTTP requests
and parameters required, refer to the [Google identity platform
documentation](https://developers.google.com/identity/protocols/oauth2/web-server#offline).

To exchange a refresh token for an access token, make an HTTPS POST call to
the Google OAuth 2.0 token endpoint. The following snippet shows an example
request and response:

### Request

```
curl -L -X POST 'https://oauth2.googleapis.com/token' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'client_id=client-id&client_secret=client-secret&refresh_token=refresh-token&grant_type=refresh_token'
```

### Response

```
{
  "access_token": "access-token",
  "expires_in": 3599,
  "scope": "scope-list",
  "token_type": "Bearer",
  "refresh_token": "refresh-token",
  "refresh_token_expires_in": 112154
}
```

### When to refresh a token

Refresh tokens on-demand as part of the natural progression of a user's active
session when access tokens are expired or close to expiration. Avoid refreshing
tokens in batches (for example, using a scheduled `cron` job or service to
refresh tokens for all users at a fixed time).

Refreshing tokens in batches is not recommended for the following reasons:

- Batch refreshing prevents aligning token updates with active user sync patterns. While you can use the [Get Devices](https://developers.google.com/health/endpoints#find-device-information) call to see a user's last sync time, this requires an additional OAuth scope that users are not obligated to approve.
- Batch processing updates tokens that don't need to be refreshed, causing redundant processing overhead for both your systems and Google's servers.
- If a network issue or server outage occurs during a batch refresh, all affected user tokens are impacted at once. Refreshing tokens individually during the natural progression of user syncs isolates the impact of transient failures to a single user.
- Diagnosing problems is more difficult with batch jobs. Because batch requests happen less frequently and generate a flood of log entries all at once, pinpointing the start of an incident is harder.
- High-concurrency spikes in token requests during batch runs increase the likelihood of hitting rate limits or experiencing intermittent authentication errors.

### Token behavior during testing

Be aware of how refresh tokens behave depending on your Google Cloud
project's publishing status:

- **Testing Mode:** If your OAuth consent screen is configured with a "Testing" publishing status, the refresh tokens issued are time-based and expire after 7 days. During this period, you will receive a single refresh token that remains valid and usable for obtaining new access tokens until it reaches its expiration date.
- **Published Mode:** Once your app is moved to "In Production" status, refresh tokens generally don't expire unless they are revoked or remain unused for a prolonged period (typically six months).

For a seamless user experience, ensure you publish your application
before it is moved into a production environment to avoid 7-day token
expirations.

## Generate sample data

Google doesn't provide pre-populated sample or mock health data. To test your
integration, you must generate your own test data. Use any of the following
methods to generate sample data for your test users:

- **Wear a tracker:** Wear a Fitbit tracker, Pixel Watch, or other smartwatch compatible with the Google Health app and walk around to generate steps, heart rate, and workout data.
- **Enable mobile tracking:** Enable MobileTrack in the Google Health app and walk around with your mobile device.
- **Log data manually:** Manually enter health metrics (such as sleep, weight, water, or food intake) through the Google Health app.
- **Write data using the API:** Send write requests (such as `POST` or `PATCH`) directly to the REST API endpoints to programmatically populate data. For more details on creating and updating data points, see the [REST reference documentation](https://developers.google.com/health/reference/rest/v4/users.dataTypes.dataPoints).

## Cross-Account Protection (RISC API)

Enable Risk and Incident Sharing and Coordination (RISC) if you want to be
notified of changes to event tokens or account linking, such as disconnected
accounts or revoked tokens, to clean up stored tokens and update UI connection
status. Enabling the RISC API is optional.

To enable the RISC API for your Google Cloud project:

1. Open the [RISC API](https://console.developers.google.com/apis/library/risc.googleapis.com) page in the Google Cloud console. Make sure the project you use for the Google Health API is selected.
2. Read the [RISC Terms](https://console.cloud.google.com/tos?id=risc) and ensure you understand the requirements.
3. Click **Enable** if you consent to the terms.

After enabling the API, you must create and register an HTTPS endpoint to
receive and validate the event tokens sent by Google.

For more information on Cross-Account Protection and RISC, see
[Protect user accounts with Cross-Account Protection](https://developers.google.com/identity/protocols/risc).