> This is part 1 of 8 of the full documentation (pages 1–100 of 727).
> The content is paginated: fetch every part to see all of it.
> Next part: https://docs.tryterra.co/llms-full.txt/1
> Page index: https://docs.tryterra.co/llms.txt

# Terra documentation

Terra is one API for wearables, health apps, sensors, and blood tests.

Every provider has its own API, data format, and authentication. Terra integrates with hundreds of them, normalises their data into one schema, and handles authentication, so you never build or maintain an integration yourself.

## Get started

1. [Create an account and get your API keys](/introduction/account-setup-and-api-keys).
2. Read [Core concepts](/introduction/core-concepts) for the terms used throughout the docs.
3. Follow a quickstart:
   * [Unified API quickstart](/unified-api/quickstart): connect one user's wearable and receive their data.
   * [Order your first test](/vantage-api/ordering-your-first-test): place a sandbox Vantage order and receive its webhooks.

## Unified API

The [Unified API](/unified-api/getting-started) gives you activity, sleep, body, and nutrition data from 500+ wearables and apps, delivered to your backend as it arrives. Most apps follow these steps in order.

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Choose sources and data types</strong></td><td>Pick the providers your users can connect and the data Terra sends.</td><td><a href="/unified-api/setting-up-data-sources">Data sources and data types</a></td></tr><tr><td><strong>Add a destination</strong></td><td>Send data to a webhook, a database, cloud storage, or a queue.</td><td><a href="/destinations/setting-up-data-destinations">Overview</a></td></tr><tr><td><strong>Authenticate users</strong></td><td>Open the Terra widget from your app and store the user ID it returns.</td><td><a href="/unified-api/authentication-flow">User authentication</a></td></tr><tr><td><strong>Receive data events</strong></td><td>Handle new data as it arrives, and request history for new users.</td><td><a href="/unified-api/receiving-data-updates">Health data events</a></td></tr><tr><td><strong>Mobile SDKs</strong></td><td>Read Apple Health, Health Connect, and Samsung Health from your iOS, Android, React Native, or Flutter app.</td><td><a href="/mobile-sdks/mobile-only-sources">Overview</a></td></tr><tr><td><strong>Troubleshooting</strong></td><td>Find out why a user's data is missing and how to fix it.</td><td><a href="/unified-api/debugging-faq">Troubleshooting</a></td></tr></tbody></table>

## Vantage API

The [Vantage API](/vantage-api/overview) lets you order blood and DNA test kits, track fulfilment, and receive lab results in FHIR format. Most apps follow these steps in order.

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Set up access</strong></td><td>Get Vantage access, authenticate requests, and configure your webhook endpoint.</td><td><a href="/vantage-api/account-setup-and-api-keys">Account setup and authentication</a></td></tr><tr><td><strong>Order a test</strong></td><td>Browse the catalog and place an at-home or go-to-lab order in sandbox.</td><td><a href="/vantage-api/ordering-your-first-test">Ordering your first test</a></td></tr><tr><td><strong>Track orders</strong></td><td>Follow fulfilment through webhooks and fetch order status history.</td><td><a href="/vantage-api/webhooks">Webhooks</a></td></tr><tr><td><strong>Fetch results</strong></td><td>Download results as FHIR documents and read the Bundle structure.</td><td><a href="/vantage-api/results">Results</a></td></tr><tr><td><strong>Acknowledge results</strong></td><td>A mandatory step: patients cannot see results until you acknowledge them.</td><td><a href="/vantage-api/acknowledging-results">Acknowledging results</a></td></tr><tr><td><strong>Go to production</strong></td><td>Run the checklist before moving from sandbox to production.</td><td><a href="/vantage-api/going-to-production">Going to production</a></td></tr></tbody></table>

## More products

Add these alongside the Unified API or Vantage API as you need them.

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>AI Interface</strong></td><td>Read access to a user's health data for your AI agents, over MCP.</td><td><a href="/ai-interface/ai-interface">Overview</a></td></tr><tr><td><strong>Models</strong></td><td>Ready-to-use wellness insights computed from a user's data, returned from one endpoint.</td><td><a href="/models/models">Overview</a></td></tr><tr><td><strong>Graphs</strong></td><td>Charts of your users' health data, built in the Terra dashboard and embedded in your product.</td><td><a href="/graphs/graphs">Overview</a></td></tr><tr><td><strong>Health Scores</strong></td><td>Adaptive health and fitness scores computed from a user's connected data.</td><td><a href="/user-engagement/health-scores">Health Scores</a></td></tr><tr><td><strong>Planned Workouts API</strong></td><td>Structured workouts pushed to users' devices and training platforms.</td><td><a href="/planned-workouts-api/overview">Overview</a></td></tr><tr><td><strong>Routes API</strong></td><td>GPS routes pushed to users' Garmin, COROS, Wahoo, and Hammerhead devices.</td><td><a href="/routes-api/overview">Overview</a></td></tr><tr><td><strong>Streaming API</strong></td><td>Live heart rate, steps, and distance from BLE and ANT+ devices, delivered to your websocket listener.</td><td><a href="/streaming-api/getting-started">Overview</a></td></tr><tr><td><strong>Teams API</strong></td><td>Data aggregated across squads, matches, and individual athlete tests.</td><td><a href="/teams-api/getting-started">Overview</a></td></tr><tr><td><strong>Lab Reports</strong></td><td>Lab report PDFs converted into structured, standardised biomarker data.</td><td><a href="/lab-reports/lab-reports">Overview</a></td></tr></tbody></table>

Run a health platform and want your API available through Terra? See [Integration Partners](/integration-partners/overview).

## Developer tools

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Terra CLI</strong></td><td>Set up, manage, and debug your Terra setup from the terminal, for you and your AI coding agent.</td><td><a href="https://docs.tryterra.co/developer-tools/terra-cli/terra-cli">https://docs.tryterra.co/developer-tools/terra-cli/terra-cli</a></td></tr><tr><td><strong>Agent skills</strong></td><td>Terra skills for Claude Code, Cursor, Copilot, and other coding agents.</td><td><a href="https://docs.tryterra.co/developer-tools/agent-skills">https://docs.tryterra.co/developer-tools/agent-skills</a></td></tr><tr><td><strong>Example apps</strong></td><td>Complete Terra integrations you can scaffold locally with one command.</td><td><a href="https://docs.tryterra.co/developer-tools/example-apps">https://docs.tryterra.co/developer-tools/example-apps</a></td></tr></tbody></table>


# Account setup and API keys

This guide walks you through creating your Terra account and obtaining the API keys necessary to start integrating with our services.

{% stepper %}
{% step %}

#### Create your Terra API account

* **Sign Up:** Create an account at the Terra API [Registration Page](https://dashboard.tryterra.co/user/signup).
* **Onboarding:** Follow the Terra the onboarding flow and fill in the required information (email, password, company details, etc.) when prompted.
  {% endstep %}

{% step %}

#### Select plan

* **Setup:** During onboarding you'll be prompted to select your plan and enter billing details. Select the plan that best fits your requirements.
* **Manage plan:** Once signed up, you can manage view your current plan and billing details within the *Terra Dashboard* under *Settings.* Ensure your account and subscription are active to maintain uninterrupted API access.
  {% endstep %}

{% step %}

#### Obtain API keys

* **Get keys from dashboard:** Once your account is setup, go to the [Terra Dashboard](https://dashboard.tryterra.co/dashboard/) and click on *API Keys* in the Navbar. Here you can copy your *Developer ID* and *API Keys*.
* **Credentials per environment:** Terra maintains separate credentials for *testing*, *staging*, and *production* environments. There is a [user cap](/unified-api/understanding-terra-environments) on *testing* and *staging*.
  {% endstep %}

{% step %}

#### Start using Terra API!

* **Follow API Docs**: You're now all set to use Terra API. We recommend that you start with the [**Unified API.**](/unified-api/getting-started)
* **Keep secret:** Never share your x-api-key publicly or embed it directly in client-side code (e.g., mobile apps, frontend JavaScript).
* **Backend Use:** API keys requiring this level of access (like your main x-api-key) should typically be used only from your secure backend server.
  {% endstep %}
  {% endstepper %}

{% prompt description="Set up the Terra CLI and get your API keys" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Install the Terra CLI, log in, and give me the dev-id and API key for my testing environment.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}


# Core concepts

Learn the terms and building blocks shared across Terra products.

Your Terra account has one or more environments, such as testing and production. Each environment has its own credentials, users and destinations, and every Terra product you use works inside it.

| Product     | Takes in                                  | Sends results to        |
| ----------- | ----------------------------------------- | ----------------------- |
| Unified API | Data from wearables and health apps       | Your destinations       |
| Lab Reports | Lab report files and DXA scans you upload | Your destinations       |
| Vantage API | Test orders you place                     | The Vantage webhook URL |

## Credentials

Every Terra product uses the same two credentials. Find both under **API keys** in the header bar of the Terra Dashboard. Learn more about [account setup and API keys](/introduction/account-setup-and-api-keys).

| Credential              | Safe to expose | Description                                                                                                    |
| ----------------------- | -------------- | -------------------------------------------------------------------------------------------------------------- |
| Developer ID (`dev-id`) | Yes            | Identifies one environment in your account. It works like a username.                                          |
| API key (`x-api-key`)   | No             | Authenticates your requests and proves they come from the owner of the developer ID. Treat it like a password. |

Send both as headers on every request. The Vantage API also accepts them as [HTTP Basic auth](/vantage-api/account-setup-and-api-keys#authentication).

{% hint style="warning" %}
Never put your API key in client-side code, a mobile app, or a public repository. Call Terra from your server.
{% endhint %}

## Environments

Each environment has its own developer ID. Users, destinations and settings belong to one environment and are not shared with the others, so you can build and test without touching production data. Learn more about [Terra environments](/unified-api/understanding-terra-environments).

## End users and reference IDs

An end user is the real person whose data you are working with: the person wearing the device, uploading the lab report, or taking the test.

Terra does not know who the end user is in your system. When you connect a wearable, upload a report or place an order, pass your own ID for that person, such as a username, email address or database ID. Terra stores it as a reference ID and returns it with the result, so you can match the data back to the right person.

| Product     | Reference ID field          |
| ----------- | --------------------------- |
| Unified API | `reference_id`              |
| Lab Reports | `reference_id`              |
| Vantage API | `client_order_reference_id` |

## Destinations

A destination is where Terra sends what a product produces: a webhook on your server, a SQL database, cloud storage such as Amazon S3, a queue such as Amazon SQS or Kafka, or a database such as MongoDB, Firestore or Supabase. Add destinations on the [Connections page](https://dashboard.tryterra.co/dashboard/connections) of the dashboard.

A destination receives every event type unless you limit it with `destination_event_types`. Learn more about [destinations](/destinations/setting-up-data-destinations).

## Events

An event is a JSON payload Terra sends to tell you something happened, such as new data arriving or a status changing. Each product has its own events, described in its section below.

## API versions

Terra versions its APIs by date. A breaking change ships under a new date. Additive changes, such as a new field, reach every version.

Choose a version for a request with the `X-Terra-Version` header. Without it, the request uses the version your account is pinned to, which is the latest version at the time of your first request.

One date works across every product. Each product serves its newest version on or before the date you send. For example, if you send `2026-10-25`, the Vantage API serves its `2026-10-15` version and Lab Reports serves its `2026-10-21` version. Learn more about [versioning](/vantage-api/versioning).

## Unified API

The [Unified API](/unified-api/getting-started) reads health and fitness data from wearables and apps and sends it to your destinations in one format.

### Sources

A source is where health and fitness data comes from, such as Fitbit, Garmin or Apple Health. Other pages also call a source a provider or an integration. Enable sources on the [Connections page](https://dashboard.tryterra.co/dashboard/connections), and see every source in the [supported integrations list](https://docs.tryterra.co/unified-api/supported-integrations#integrations-list).

Sources send new data to Terra in one of two ways:

| Type         | Description                                                                                                                                |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Event-driven | The provider notifies Terra as soon as the wearable's app syncs new data to the provider's cloud. This is the fastest way to get new data. |
| Polled       | The provider has no notifications, so Terra checks its servers for new data every 15 minutes by default, and never more often.             |

### Users

A user is one connection between Terra and one wearable account, such as one Fitbit account or one Garmin account. Each user has its own `user_id`, and Terra returns your `reference_id` on the user in every event.

One end user can have several users. If someone connects both their Fitbit and their Garmin, Terra creates two users with different `user_id`s that share one `reference_id`.

If an end user connects the same provider account again with the same `reference_id`, Terra replaces the old user with a new one, with a new `user_id`. Connecting a different account on the same provider adds a second user and leaves the first in place.

### Data types

The Unified API has eight data types, each with a fixed structure. Learn more about every field in the [data models reference](https://docs.tryterra.co/reference/health-and-fitness-api/data-models).

| Data type      | Description                                                                                                                                   |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `activity`     | One completed workout with a start and end time, such as a run recorded between pressing start and stop on a Garmin watch.                    |
| `athlete`      | The end user's profile on the provider, such as name, age, sex, location and devices.                                                         |
| `body`         | The end user's body metrics for one day, such as weigh-ins and blood glucose readings.                                                        |
| `daily`        | The end user's total activity for one day.                                                                                                    |
| `hormone`      | One hormone test, with levels such as LH, FSH and hCG.                                                                                        |
| `menstruation` | One day of the menstrual cycle: the current phase and anything logged that day.                                                               |
| `nutrition`    | The food an end user logged in one day, from apps such as MyFitnessPal.                                                                       |
| `sleep`        | One completed sleep session. If the device tracks it, the start time can be when the end user got into bed rather than when they fell asleep. |

`daily` and `body` payloads arrive several times a day. Each one holds the running total for that day so far, so overwrite the stored payload for that date with the latest one.

### Event delivery

Terra sends each event to each of your destinations as a separate delivery. A delivery is one or more attempts: the first send, plus any retries and resends. Learn more about [event delivery](/destinations/events).

### Large requests

A request for more than one calendar month of data is a large request. Terra processes it in the background and sends the data to your destinations in chunks of 10 MB or less, so a large request must use `to_webhook=true`, which is the default.

## Lab Reports

[Lab Reports](/lab-reports/lab-reports) turns lab report PDFs, images and DXA scans into structured biomarker data.

Each upload creates a session, which tracks the report through extraction, standardization and delivery. Terra classifies the file as a clinical lab report or a DXA scan, matches each result to a known biomarker, and maps its unit to a standard UCUM code. It does not convert values between units.

When processing ends, Terra sends a `lab_report.completed` or `lab_report.failed` event to your destinations. Learn more about [sessions and delivery](/lab-reports/core-concepts).

## Vantage API

The [Vantage API](/vantage-api/overview) orders blood and DNA tests and returns the results.

You order from a catalog of products, grouped by product type such as blood or DNA. Each product has variants, and a variant is what you order. Samples are collected at home, by kit or a visiting phlebotomist, or at a lab.

An order is one purchase for a recipient, and holds one or more order items. Each order item is tracked on its own: kit activation, results and acknowledgment all belong to the order item. The person who takes the test, the test taker, can be someone other than the recipient.

Vantage sends an event when an order's fulfilment status or an order item's results status changes. It sends events to one [webhook URL per environment](/vantage-api/account-setup-and-api-keys#configure-your-webhook-endpoint), not to your destinations. Learn more about [orders, results and status lifecycles](/vantage-api/core-concepts).

## Streaming API

The [Streaming API](/streaming-api/getting-started) sends live readings, such as heart rate, from a wearable to your backend over WebSockets while the end user wears it.

| Term     | Description                                                                                                                              |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Device   | A wearable that streams over Bluetooth Low Energy (BLE), ANT+, or its own Bluetooth protocol (Apple Watch, Wear OS and Samsung watches). |
| Phone    | The end user's iOS or Android phone. It connects to the device and runs your app with the Terra RT SDK.                                  |
| Producer | A connection that sends data to Terra. The RT SDK on the phone is the producer.                                                          |
| Broker   | Terra. It receives data from producers and passes it to every consumer connected to that stream.                                         |
| Consumer | A connection that receives the stream, usually your backend.                                                                             |

Each WebSocket connection authenticates with its own short-lived token, minted by your backend. Learn more about [streaming authentication](https://docs.tryterra.co/reference/streaming-api/api-endpoints).

## See also

* [Account setup and API keys](/introduction/account-setup-and-api-keys)
* [Unified API quickstart](/unified-api/quickstart)
* [Planned Workouts API core concepts](/planned-workouts-api/core-concepts)
* [Routes API core concepts](/routes-api/core-concepts)


# Overview

How the Unified API gets your users' wearable and health app data to your backend, and the steps to build on it.

The Unified API connects your app to your users' wearables, sensors, and health apps through one integration. Terra handles each provider's authentication, API, and data model, normalises the data into one schema, and pushes it to your backend as it arrives. You integrate once and get Garmin, Fitbit, Oura, Apple Health, and 500+ other sources.

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-e50ceaf6229172c5da05658cc12ea8cb917e9380%2Funified-api-data-flow.png?alt=media" alt="A user&#x27;s wearable syncs to its provider, Terra fetches and normalises the data, and sends it to your backend, which serves your mobile and web frontends" width="563"><figcaption><p>Data flows from the provider through Terra to your backend</p></figcaption></figure>

## How it works

1. **A user connects a source.** Your app opens the Terra widget, an embeddable flow where the user picks their provider and logs in. Terra returns a `user_id` for that connection and keeps the provider tokens refreshed from then on.
2. **Terra normalises the data.** Whatever the provider's format, you receive the same JSON schema for every source, so you code against one set of models.
3. **Terra pushes it to your destination.** As soon as the provider makes new data available, Terra sends it backend to backend to the destination you configured: a webhook, a SQL database, MongoDB, Firestore, cloud storage on S3, GCS, or Azure, or a queue on SQS or Kafka.

The API is event based, so you do not poll for updates. You request data in one case: to backfill history from before the user connected, for example to establish baselines or train a model on a new user's past months. See [Historical data requests](/unified-api/requesting-historical-data).

### Delivery and security

Data is encrypted in transit, and every webhook is signed so you can check it came from Terra. If your server is down, Terra retries, and you can see every delivery attempt in the dashboard. See [Webhooks](/destinations/webhooks).

## What you receive

| Data type    | What it covers                                                                                      |
| ------------ | --------------------------------------------------------------------------------------------------- |
| Activity     | A workout: heart rate, distance, route, pace, power, calories, and strength sets.                   |
| Sleep        | A night's sleep or a nap: stages, heart rate, HRV, breathing, and sleep scores.                     |
| Daily        | The day so far: steps, calories, active minutes, stress, and daily scores. Updated through the day. |
| Body         | Body readings: weight, body fat, blood pressure, glucose, ECG, and temperature.                     |
| Nutrition    | Meals and drinks logged, with calories, macros, and micronutrients.                                 |
| Menstruation | Cycle tracking: phase, day in cycle, flow, and fertility window.                                    |
| Hormone      | Hormone levels from at-home tests: LH, E3G, PdG, hCG, and FSH.                                      |
| Athlete      | The user's profile at the provider: name, sex, date of birth, and location.                         |

Every field is listed in the [data models reference](https://docs.tryterra.co/reference/health-and-fitness-api/data-models) and the [OpenAPI spec](https://github.com/tryterra/openapi). All fields are nullable: a field the provider does not supply is `null`, so the shape is the same for every source.

## Web sources and mobile-only sources

| Source type | Examples                                                                                                                     | How it connects                                                                                                                                                      |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Web         | Garmin, Fitbit, Oura, Strava, and [500+ more](https://docs.tryterra.co/unified-api/supported-integrations#integrations-list) | Terra reads the provider's cloud API. Nothing extra to build.                                                                                                        |
| Mobile-only | Apple Health, Samsung Health, Health Connect                                                                                 | These have no cloud API for third parties, so your mobile app reads them with the [Terra mobile SDKs](/mobile-sdks/mobile-only-sources) and sends the data to Terra. |

Either way, the data reaches your destination in the same format. Only add the SDK if you need one of those three sources.

Terra has no rate limits of its own. Providers do, and Terra handles retries and backoff for you.

## Build on the Unified API

Most apps build in this order. The [Quickstart](/unified-api/quickstart) runs through the same steps from the dashboard in a few minutes.

| Step                   | What you do                                                                                           | Pages                                                                                                                                                                  |
| ---------------------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. Set up your account | Pick an environment, then choose the providers your users can connect and the data types Terra sends. | [Environments](/unified-api/understanding-terra-environments), [Data sources and data types](/unified-api/setting-up-data-sources)                                     |
| 2. Add a destination   | Tell Terra where to send data: a webhook, a database, cloud storage, or a queue.                      | [Destinations](/destinations/setting-up-data-destinations), [Webhooks](/destinations/webhooks)                                                                         |
| 3. Authenticate users  | Open the Terra widget from your app and store the `user_id` from the auth event.                      | [User authentication](/unified-api/authentication-flow), [Terra authentication widget](/unified-api/implementation-terra-widget)                                       |
| 4. Receive data        | Handle data events as they arrive, and backfill history for new users.                                | [Health data events](/unified-api/receiving-data-updates), [Historical data requests](/unified-api/requesting-historical-data), [Event delivery](/destinations/events) |
| 5. Add mobile sources  | Only if you need Apple Health, Health Connect, or Samsung Health.                                     | [Mobile SDKs](/mobile-sdks/mobile-only-sources)                                                                                                                        |

Some providers need extra setup: your own developer keys for a provider are covered in [Dedicated source API keys](/unified-api/dedicated-data-source-api-keys), and letting each end user bring their own OAuth app is covered in [Per-user OAuth apps](/unified-api/per-user-oauth-apps). If data stops arriving, start with [Troubleshooting](/unified-api/debugging-faq).

{% @storylane/embed subdomain="app" url="<https://app.storylane.io/share/8qriif1vn3mf>" linkValue="8qriif1vn3mf" %}

## Next steps

* [Quickstart](/unified-api/quickstart): connect a wearable and see its data arrive.
* [Destinations](/destinations/setting-up-data-destinations): choose where Terra sends data.
* [Pricing](/unified-api/pricing): how Unified API credits work.


# Quickstart

Connect a wearable and see its data arrive, in four steps from the Terra dashboard.

Terra connects your users' wearables and health apps, then sends their data to you. This page walks through that once, from the [Terra dashboard](https://dashboard.tryterra.co/), using your own wearable account as the test user. No code needed.

{% embed url="<https://www.youtube.com/watch?v=rkvKe4xefwY>" %}
2 minute video walkthrough
{% endembed %}

## Before you begin

* A Terra account. See [Account setup](/introduction/account-setup-and-api-keys).
* A wearable or health app account to connect, such as Fitbit, Oura, or Garmin.
* Somewhere to receive data. [webhook.site](https://webhook.site/) gives you a URL that shows every payload Terra sends, with nothing to install. Step 2 also covers running your own local server.

## Connect your first wearable

{% stepper %}
{% step %}

### Choose your data sources

Go to **Connections** in the dashboard and, under **Sources**, enable the wearables and apps you want your users to connect. Enable the one you own for this test. Enabled sources are the ones your users can pick from.
{% endstep %}

{% step %}

### Choose where data goes

On the same page, under **Destinations**, add a **Webhook** and paste your webhook.site URL. Terra sends every user's data here as it becomes available. A webhook is the simplest destination; databases, cloud storage and queues are also supported.

{% hint style="info" %}
**Two ways to get a webhook URL**

**webhook.site**: open [webhook.site](https://webhook.site/) and copy *Your unique URL*. Payloads appear on the page as they arrive. Nothing to install.

**Your own server**: run a small web server on your machine, then expose it to the internet with [ngrok](https://ngrok.com/). `ngrok http 8080` prints a public URL to paste into the dashboard.

```python
import flask

app = flask.Flask(__name__)

@app.route("/", methods=["POST"])
def receive():
    print(flask.request.get_json())
    return "", 200

if __name__ == "__main__":
    app.run(host="localhost", port=8080)
```

{% endhint %}
{% endstep %}

{% step %}

### Connect a wearable

Go to **Authentication**. This page previews the Terra widget, the screen your users see when they connect. Open it, pick the source you enabled, and log in with your own account.

This is the flow your users will go through, so the login is the provider's own, not Terra's.
{% endstep %}

{% step %}

### See the data arrive

Switch to your webhook.site tab. The first payload is an `auth` event confirming the connection. Data payloads follow as the provider syncs: `activity`, `sleep`, `daily`, `body`, and `nutrition`.

To see a data payload right away, go to **Data generator** in the dashboard and send a sample to your destination.
{% endstep %}
{% endstepper %}

That is the whole loop: a user connects once, and Terra keeps sending their data to your destination.

## Optional: Run it with your coding agent

If you use Claude Code, Cursor, or another coding agent, paste this prompt. The agent does the steps above through the Terra CLI and reports back.

{% prompt description="Run the quickstart with your coding agent" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Set up my Terra testing environment: enable Fitbit and Oura, add a webhook destination pointing at my webhook URL, and give me the dev-id and API key. Then create a widget session for reference_id demo-user and open the URL for me. Once I have connected, confirm the connection is active and show me the first event Terra delivered.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## Build it into your app

Your app repeats the same four steps, with two differences.

* **Your app opens the widget for each user.** Your backend creates a widget session with one API call and sends the user to the URL it returns. See [Terra authentication widget](/unified-api/implementation-terra-widget). The call needs your API keys, found under **API Keys** in the dashboard.
* **Your server receives the data.** Replace webhook.site with your own endpoint. See [Webhooks](/destinations/webhooks) for handling payloads and verifying they came from Terra.

Keep your API key on your server, never in an app or web page.

Each connection gets a `user_id` from Terra. Every payload carries it, and it is how you request that user's data. Pass your own identifier as `reference_id` when you open the widget, and Terra returns it alongside the `user_id` so you can match the two. See [Core concepts](/introduction/core-concepts).

## Next steps

* [Unified API example app](https://docs.tryterra.co/developer-tools/example-apps/terra-basecamp): a complete integration you can scaffold with one command.
* [User authentication](/unified-api/authentication-flow): open the widget from your own app.
* [Historical data requests](/unified-api/requesting-historical-data): get data from before the user connected.
* [Mobile SDKs](/mobile-sdks/mobile-only-sources): Apple Health, Samsung Health, and Health Connect need the mobile SDK.


# Environments

Learn the three Terra environments, testing, staging and production, and the user limit in each.

Every Terra account has three environments. This page covers what each one allows and how to stay within the user limits.

* **Testing**: you'll have access to 50 [users](https://docs.tryterra.co/introduction/core-concepts#users)
* **Staging**: you'll have access to 50 [users](https://docs.tryterra.co/introduction/core-concepts#users)
* **Production**: unlimited

You can configure each environment separately on your [Terra dashboard](https://dashboard.tryterra.co/).

{% prompt description="List your environments and set a default" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
List my Terra environments with how many users each has, and set staging as my default.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## User limits

Testing and staging each have a limit of 50 users. These test users are provided by Terra on top of any plan.

If you reach the user limit, deregister the testing accounts you no longer need using the [https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser "mention") endpoint.

## Rate limits

Terra does not impose any rate limits on the REST API. API requests are generally not necessary unless you are backfilling historical data.

## Next steps

* [Data sources and data types](/unified-api/setting-up-data-sources): choose the providers your users can connect.
* [Destinations](/destinations/setting-up-data-destinations): choose where Terra sends data.
* [User authentication](/unified-api/authentication-flow): open the widget from your app.


# Data sources and data types

Choose which providers your users can connect, which data types Terra sends, and which permissions each provider asks for.

A data source is a provider your users connect, such as Garmin, Fitbit or Oura. You choose which sources are available, which data types Terra sends to your destination, and, for some sources, which permissions the user is asked to grant. All three are set in the Terra dashboard.

## Enable data sources

1. Open [Connections](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard.
2. Click **Add New** and choose from 150+ integrations.
3. Toggle each integration on <img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-681864500ace25f72104d6e6884b4c985fa75d9f%2FCapture%20d%E2%80%99%C3%A9cran%202025-03-29%20%C3%A0%2001.18.45.png?alt=media" alt="" data-size="line"> to activate it.

{% prompt description="Enable data sources from the terminal" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Enable Garmin, Fitbit, and Oura in my staging environment.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

The Unified API supports three kinds of source:

* Wearables and connected devices, such as Oura, Fitbit, Garmin and Withings.
* Nutrition and menstruation trackers, such as MyFitnessPal and MacrosFirst.
* Medical devices, such as Omron and Tenovi.

The full list is in the [supported integrations table](https://docs.tryterra.co/unified-api/supported-integrations).

### Sources that need extra setup

These providers need your own developer app or keys before you can enable them:

* <img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FOmTLYIUYupqUciIkooJp%2Fwhoop.webp?alt=media&amp;token=d637cb9b-c688-4231-a02a-6b8dd746f1b4" alt="" data-size="line"> [WHOOP](/unified-api/whoop)
* <img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2F54UpDHsllK0GwQKOdX5K%2Fdexcom.webp?alt=media&amp;token=2c8f6fb2-4631-4b2b-b13c-0afe6ac29d96" alt="" data-size="line"> [Dexcom](/unified-api/dexcom)
* <img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FpbdxMhNu0V3SRj1tLlOF%2Fhuawei.png?alt=media&amp;token=dc565503-74a8-41f4-89cd-978a09b7b231" alt="" data-size="line"> [Huawei](/unified-api/dedicated-data-source-api-keys#huawei)
* <img src="https://api.tryterra.co/v2/static/assets/img/app_icons/strava.webp" alt="" data-size="line"> [Strava](/unified-api/dedicated-data-source-api-keys#strava)
* <img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FJcVmlm6tCu4KPeV8pRC7%2Fvirtuagym.webp?alt=media&amp;token=d4d45b97-595c-437f-9094-d94d34afae7d" alt="" data-size="line"> [Virtuagym](/unified-api/dedicated-data-source-api-keys#virtuagym)

{% hint style="danger" %}

## Important Note

The Unified API **CANNOT** be used to connect to the following integrations by itself:

<img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FDH2JWDtg632mUQlEdrLH%2F4p3k173m8ihe71872bi9r0292q-0af5626e815091005bacb793985c1870.png?alt=media&amp;token=062c917e-02fe-4029-9809-fc881cf09de3" alt="" data-size="line"> **Apple Health**

<img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2F0lTv9KpldVVjBdg3JJQs%2Fimgbin_samsung-galaxy-samsung-health-samsung-electronics-android-png.png?alt=media&amp;token=b58f3118-a2e1-4b09-9d30-4f862253adb6" alt="" data-size="line"> **Samsung Health**

<img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FmotL0wnZKiEWOKt46zOU%2Fvecteezy_google-fit-icon-logo-symbol_22484515.png?alt=media&amp;token=a2d0ae73-5116-49fd-8ce1-0f7b5e6f716b" alt="" data-size="line"> **Health Connect**

***

These integrations are **mobile-based integrations.** This means that:

* They require a **mobile app** with a **Mobile SDK integration** on the user's device to fetch the data.
* They not offer any sort of web API or web-based data retrieval.

To connect to **Apple Health, Google Health,** **Samsung Health,** please refer to [the Terra **Mobile SDK**](/mobile-sdks/mobile-only-sources)

To connect any other **data source (e.g. Oura, Fitbit, Garmin),** please use Terra's **Web** **API** from your backend.
{% endhint %}

Some of the supported data sources are developed on agreements subject to be updated by them. Their APIs can be modified without notifying Terra or 3rd parties, which could cause disruption in the service beyond our control. Those integrations are any of the ones with **"Integration Credentials"** marked as **N/A** in the [Supported Integrations table in the API Reference](https://docs.tryterra.co/unified-api/supported-integrations).

## Choose data types

Choose which data types Terra sends to your destination. Open the [data types settings](https://dashboard.tryterra.co/dashboard/connections?open=edit_scopes) in your Terra dashboard and select from:

* Activity
* Daily
* Body
* Sleep
* Nutrition
* Menstruation

This applies to every data source. Turn on **Samples** to receive granular data: a list of readings at specific timestamps.

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-6d440dde90d7ce3c93d10c45702241b7d675acfc%2FCapture%20d%E2%80%99%C3%A9cran%202025-03-28%20%C3%A0%2015.01.44.png?alt=media" alt=""><figcaption><p>Without "Samples"</p></figcaption></figure>

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-28d65c4fb80ba6434bf54a6e748b3497d5a70ff6%2FCapture%20d%E2%80%99%C3%A9cran%202025-03-28%20%C3%A0%2014.56.39.png?alt=media" alt=""><figcaption><p>With "Samples"</p></figcaption></figure>

## Limit permissions for a source

Some data sources let you restrict the scopes requested from your end user. The widget then shows only those permissions.

1. Open **Connections** in your Terra dashboard.
2. Select the data source.
3. Choose **Edit**.
4. Open the **Edit Permissions** tab and choose your scopes.

{% @supademo/embed url="<https://app.supademo.com/demo/clzviqwur09rmo0qpurjz6y3l>" demoId="clzviqwur09rmo0qpurjz6y3l" %}

## Next steps

* [Destinations](/destinations/setting-up-data-destinations): choose where Terra sends data.
* [User authentication](/unified-api/authentication-flow): open the widget from your app.
* [Dedicated source API keys](/unified-api/dedicated-data-source-api-keys): use your own developer credentials for a source that needs them.


# Supported integrations

See every integration Terra supports, its enum value, how it syncs, and whether you need your own credentials.

Every integration you can connect through the Unified API. Use the enum value wherever the API takes a provider.

## Integrations list

{% hint style="info" %}
Event-driven integrations send new data as soon as it is available.

Periodically fetched integrations are polled by Terra every 15 minutes by default for new data.

Managed integrations work with Terra's credentials, so you don't need an account with the integration. Some also let you use your own credentials, created in the integration's developer portal.

Required integrations need your own credentials, created in the integration's developer portal and added to your Terra dashboard before end users can connect.

N/A means there are no integration credentials to set up.
{% endhint %}

{% hint style="warning" %}
Fitbit is retired. Google turned off the Fitbit Web API on 2 November 2026, so Fitbit connections no longer receive data and end users can't connect through Fitbit. Move your end users to Google Health (`GOOGLE_HEALTH`): see [How do I handle the Fitbit-to-Google migration?](https://docs.tryterra.co/help-center/help-topics/data-api-sdk/account-config-environments-and-going-live/fitbit-to-google-migration) and the guide to [how the Google Health API works](https://tryterra.co/blog/everything-you-need-to-know-about-google-health-new-api).
{% endhint %}

<table data-full-width="true"><thead><tr><th>Integration Name</th><th>Enum Value</th><th width="153.8">Data Sync Method<select><option value="4X1Vjoop8F9C" label="Periodically fetched" color="blue"></option><option value="SvXiL3umYKyr" label="Event-Driven" color="blue"></option></select></th><th width="95">Integration credentials<select><option value="dZJJx1IacCC5" label="N/A" color="blue"></option><option value="mQewsfArCAI8" label="Managed" color="blue"></option><option value="UrxKo3b5zPDs" label="Required" color="blue"></option></select></th><th width="155">Developer portal</th><th data-hidden>API Type<select><option value="fkaxRteZGBOK" label="Web API" color="blue"></option><option value="cSPTdjOQRXaI" label="SDK" color="blue"></option></select></th></tr></thead><tbody><tr><td>Apple</td><td>APPLE</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Cardiomood</td><td>CARDIOMOOD</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Concept2</td><td>CONCEPT2</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://log.concept2.com/developers/keys">https://log.concept2.com/developers/keys</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Coros</td><td>COROS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://support.coros.com/hc/en-us/articles/17085887816340-Submit-an-API-Application">https://support.coros.com/hc/en-us/articles/17085887816340-Submit-an-API-Application</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Core</td><td>CORE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Cronometer</td><td>CRONOMETER</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd to Cronometer team</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Dexcom</td><td>DEXCOM</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://developer.dexcom.com/docs/dexcom/getting-started/">https://developer.dexcom.com/docs/dexcom/getting-started/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Dexcom EU</td><td>DEXCOM_EU</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td>See above &#x26; contact Dexcom support</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>EatThisMuch</td><td>EATTHISMUCH</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>FatSecret</td><td>FATSECRET</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://platform.fatsecret.com/register">https://platform.fatsecret.com/register</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>FinalSurge</td><td>FINALSURGE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Fitbit</td><td>FITBIT</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://dev.fitbit.com/apps">https://dev.fitbit.com/apps</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Fitbod</td><td>FITBOD</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Strong</td><td>STRONG</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>StrongLifts</td><td>STRONGLIFTS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Lyfta</td><td>LYFTA</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Liftosaur</td><td>LIFTOSAUR</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Garmin</td><td>GARMIN</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://developerportal.garmin.com">https://developerportal.garmin.com</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Google Fit (Health Connect-based)</td><td>GOOGLEFIT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="cSPTdjOQRXaI">SDK</span></td></tr><tr><td>Google Fit</td><td>GOOGLE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://console.cloud.google.com/apis/api/fitness.googleapis.com">https://console.cloud.google.com/apis/api/fitness.googleapis.com</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Hammerhead</td><td>HAMMERHEAD</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Hevy</td><td>HEVY</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Huawei</td><td>HUAWEI</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://developer.huawei.com/consumer/en/hms/huaweihealth/">https://developer.huawei.com/consumer/en/hms/huaweihealth/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>InBody</td><td>INBODY</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://inbodyusa.com/web-api/">https://inbodyusa.com/web-api/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Intervals.icu</td><td>INTERVALS_ICU</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Lezyne</td><td>LEZYNE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Moxy</td><td>MOXY</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>MapMyFitness</td><td>MAPMYFITNESS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://developer.mapmyfitness.com/requestkey/">https://developer.mapmyfitness.com/requestkey/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>MyFitnessPal</td><td>MYFITNESSPAL</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>NutraCheck</td><td>NUTRACHECK</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Omron</td><td>OMRON</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://omronhealthcare.com/api/">https://omronhealthcare.com/api/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Omron US</td><td>OMRONUS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://omronhealthcare.com/api/">https://omronhealthcare.com/api/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Oura</td><td>OURA</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://cloud.ouraring.com/oauth/applications">https://cloud.ouraring.com/oauth/applications</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Peloton</td><td>PELOTON</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Polar</td><td>POLAR</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://admin.polaraccesslink.com/">https://admin.polaraccesslink.com/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>RideWithGPS</td><td>RIDEWITHGPS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Rouvy</td><td>ROUVY</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Samsung</td><td>SAMSUNG</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c">https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c</a></td><td><span data-option="cSPTdjOQRXaI">SDK</span></td></tr><tr><td>Suunto</td><td>SUUNTO</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Applications no longer open</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Tempo</td><td>TEMPO</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>TriDot</td><td>TRIDOT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Tredict</td><td>TREDICT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>TrainingPeaks</td><td>TRAININGPEAKS</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>TrainAsOne</td><td>TRAINASONE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>TrainerRoad</td><td>TRAINERROAD</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Virtuagym</td><td>VIRTUAGYM</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td>Bring your own key: Virtuagym Professional account → System Settings → Business Info → Advanced</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Wahoo</td><td>WAHOO</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://developers.wahooligan.com/applications">https://developers.wahooligan.com/applications</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Whoop</td><td>WHOOP</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://external-developer-portal.whoop.com/">https://external-developer-portal.whoop.com/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Catapult One</td><td>CATAPULTONE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Withings</td><td>WITHINGS</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://developer.withings.com/dashboard/welcome">https://developer.withings.com/dashboard/welcome</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Xoss</td><td>XOSS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Zepp</td><td>ZEPP</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Applications not currently open</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Zwift</td><td>ZWIFT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Xert</td><td>XERT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>BrytonSport</td><td>BRYTONSPORT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Wger</td><td>WGER</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>VeloHero</td><td>VELOHERO</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Cycling Analytics</td><td>CYCLINGANALYTICS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://www.cyclinganalytics.com/developer/api/app-creation">https://www.cyclinganalytics.com/developer/api/app-creation</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Nolio</td><td>NOLIO</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://www.nolio.io/api/">https://www.nolio.io/api/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>TrainXhale</td><td>TRAINXHALE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>KetoMojo US</td><td>KETOMOJOUS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://keto-mojo.com/developers/">https://keto-mojo.com/developers/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>KetoMojo EU</td><td>KETOMOJOEU</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td><a href="https://keto-mojo.com/developers/">https://keto-mojo.com/developers/</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Strava</td><td>STRAVA</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="UrxKo3b5zPDs">Required</span></td><td><a href="https://strava.com/settings/api">https://strava.com/settings/api</a></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Clue</td><td>CLUE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Health Gauge</td><td>HEALTHGAUGE</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>MacrosFirst</td><td>MACROSFIRST</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Aktiia</td><td>AKTIIA</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Decathlon</td><td>DECATHLON</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Flo</td><td>FLO</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>MapMyTracks</td><td>MAPMYTRACKS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Elite HRV</td><td>ELITEHRV</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Eight Sleep</td><td>EIGHTSLEEP</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td>Case by case. Contact Terra Support to be intro'd</td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Google Health</td><td>GOOGLE_HEALTH</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Health Connect</td><td>HEALTH_CONNECT</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="cSPTdjOQRXaI">SDK</span></td></tr><tr><td>Ultrahuman</td><td>ULTRAHUMAN</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Runkeeper</td><td>RUNKEEPER</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>My Macros+</td><td>MYMACROS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Boditrax</td><td>BODITRAX</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="dZJJx1IacCC5">N/A</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Trailforks</td><td>TRAILFORKS</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Sensor Bio</td><td>SENSORBIO</td><td><span data-option="4X1Vjoop8F9C">Periodically fetched</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr><tr><td>Equinox</td><td>EQUINOX</td><td><span data-option="SvXiL3umYKyr">Event-Driven</span></td><td><span data-option="mQewsfArCAI8">Managed</span></td><td></td><td><span data-option="fkaxRteZGBOK">Web API</span></td></tr></tbody></table>


# User authentication

Connect an end user's wearable or health app to Terra, then store the user ID from the auth event.

Connecting a user lets them grant your app access to a provider such as Fitbit, Garmin or Oura. Once they connect, Terra pushes their data to your destination as events, with no polling. Terra stores and refreshes the provider tokens for you.

## Before you begin

* Get your **API key** and **dev ID** from the [Terra dashboard](https://dashboard.tryterra.co/).
* [Set up a destination](/destinations/setting-up-data-destinations) where Terra sends events.
* [Enable the data sources](/unified-api/setting-up-data-sources) your users can connect.

## How authentication works

1. The user clicks **Connect device** in your app.
2. Your frontend asks your backend for a widget URL.
3. Your backend creates a widget session with `POST /api/widget/session`. See [Terra authentication widget](/unified-api/implementation-terra-widget).
4. Your frontend opens the widget URL in a new tab, or an in-app browser on mobile.
5. The user picks their provider and logs in.
6. The widget redirects to your success or failure URL with `user_id` and `reference_id` as query parameters.
7. Terra sends an `auth` event to your destination.

From then on, the user's data reaches your destination automatically.

## Try it from the dashboard

To see the flow before writing any code, connect your own device from the [Terra dashboard](https://dashboard.tryterra.co/). Your end users don't connect this way: live users go through the API.

{% prompt description="Run a user through auth and read the auth event" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Generate a widget session for reference_id test-1 and open it for me. Once I have connected, check whether the connection is active and show me the auth event.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

{% @supademo/embed url="<https://app.supademo.com/demo/clzvfyvwy08lmo0qpw5yadcf8>" demoId="clzvfyvwy08lmo0qpw5yadcf8" %}

## Handle the auth event

Terra sends an [authentication event](https://docs.tryterra.co/reference/health-and-fitness-api/event-types#authentication) to your destination whenever a user connects, disconnects, fails to connect, reconnects, or has their access revoked. Each event carries the `user_id`, the auth `status` and a `message`.

A successful `auth` event:

```json
{
    "type": "auth",
    "status": "success",
    "widget_session_id": "a9a0c7a4-c05e-4550-a973-f87a31a7c558",
    "user": {
        "scopes": "COURSE_IMPORT,WORKOUT_IMPORT,ACTIVITY_EXPORT,HEALTH_EXPORT",
        "active": true,
        "last_webhook_update": null,
        "created_at": "2024-10-07T03:45:00.000000+00:00",
        "user_id": "4735eac4-31a2-47ef-8b11-51e98d84c680",
        "reference_id": "tony_stark",
        "provider": "GARMIN"
    },
    "reference_id": "tony_stark",
    "message": "User has successfully authenticated",
    "version": "2022-03-16"
}
```

Every authentication event format is listed under [Event types](https://docs.tryterra.co/reference/health-and-fitness-api/event-types#authentication). All events you have received are in [Dashboard > Events](https://dashboard.tryterra.co/dashboard/debug).

{% prompt description="Inspect auth events and why one failed" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Show me the auth events for reference_id test-1 and explain why the last one failed.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## Store the user ID

Save the `user_id` from the auth event against your own user. Every data event carries this `user_id`, so without it you can't tell whose activity or sleep data has arrived.

The `user_id` is also on the success redirect:

```
{auth_success_redirect_url}?user_id=...&reference_id=...&resource=...
```

### When the user ID changes

Connecting the same provider again with the same `reference_id` and `dev_id` deletes the previous user record and creates a new `user_id`. This is per provider: reconnecting Fitbit doesn't affect an Apple Health connection under the same `reference_id`.

The old `user_id` disappears from the Users tab in your dashboard, though Payload History still shows data sent to it. Terra sends a `user_reauth` event with both the old and new `user_id`. Handle it and update the stored `user_id`, or new data won't match your records.

## Check your setup

Your setup is working when:

1. Your backend gets a `201` from `POST /api/widget/session` and reads the `url` field. With a custom UI, it gets a `200` from `POST /auth/authenticateUser` and reads `auth_url`.
2. The end user lands on your success redirect after connecting.
3. Your destination receives an `auth` event with `status: success`.
4. You store the `user_id` from that event against your own user.

## Next steps

* [Terra authentication widget](/unified-api/implementation-terra-widget): create a widget session and open the hosted connect screen.
* [Custom authentication UI](/unified-api/implementation-custom-ui): build your own provider buttons and generate login links.
* [Authentication redirect pages](/unified-api/customising-authentication-redirects): send the end user back to your app after they connect.


# Terra authentication widget

Create a widget session from your backend and send the end user to the hosted screen where they pick a provider and log in.

The Terra widget is a hosted screen where your end user picks their data provider and logs in. You create a **widget session** from your backend with one API call, then send the user to the URL it returns.

{% hint style="info" %}
**Already live with `/auth/generateWidgetSession`?** It keeps working today, with deprecation planned for 3 November 2026. It is documented under [Legacy endpoint](#legacy-endpoint) at the bottom of this page, with [migration notes](#migrate-from-auth-generatewidgetsession) for moving to the redesigned widget.
{% endhint %}

## Create a widget session

From your **backend**, call `POST https://access.tryterra.co/api/widget/session` with your `dev-id` and `x-api-key` headers.

{% tabs %}
{% tab title="cURL" %}
{% code title="Command Line" %}

```bash
curl --request POST --url https://access.tryterra.co/api/widget/session \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
      "reference_id": "my_first_connection",
      "auth_success_redirect_url": "https://example.com/success",
      "auth_failure_redirect_url": "https://example.com/failure"
  }'
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}

```python
import requests

response = requests.post(
    "https://access.tryterra.co/api/widget/session",
    headers={"dev-id": "<YOUR-DEV-ID>", "x-api-key": "<YOUR-API-KEY>"},
    json={
        "reference_id": "my_first_connection",
        "auth_success_redirect_url": "https://example.com/success",
        "auth_failure_redirect_url": "https://example.com/failure",
    },
)

widget_url = response.json()["url"]
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
import axios from "axios";

const { data } = await axios.post(
  "https://access.tryterra.co/api/widget/session",
  {
    reference_id: "my_first_connection",
    auth_success_redirect_url: "https://example.com/success",
    auth_failure_redirect_url: "https://example.com/failure",
  },
  { headers: { "dev-id": "<YOUR-DEV-ID>", "x-api-key": "<YOUR-API-KEY>" } }
);

const widgetUrl = data.url;
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Use `reference_id` to pass your own end user's ID. It comes back on the [authentication event](/unified-api/authentication-flow#handle-the-auth-event) and on the success redirect, so you can match the Terra [User](https://docs.tryterra.co/introduction/core-concepts#users) to your end user without any extra lookups.
{% endhint %}

### Request body

All fields are optional. With no `providers` field, the widget shows the data sources you have enabled in your [Terra Dashboard](https://dashboard.tryterra.co/).

| Field                       | Type      | Description                                                                                                                                                                                                  |
| --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `reference_id`              | string    | Your identifier for the end user (a user ID or email on your system).                                                                                                                                        |
| `providers`                 | string    | Comma-separated list of providers to show, in the order given, e.g. `"GARMIN,OURA,FITBIT"`. A single provider skips the selection screen and goes straight to that login.                                    |
| `auth_success_redirect_url` | string    | Where to send the user after a successful connection.                                                                                                                                                        |
| `auth_failure_redirect_url` | string    | Where to send the user after a failed or abandoned connection.                                                                                                                                               |
| `show_disconnect`           | boolean   | Show a disconnect button next to providers already connected under this `reference_id`. Defaults to `true` when a `reference_id` is given; set `false` to hide it.                                           |
| `multi_auth`                | boolean   | Keep the user on the widget after each successful connection so they can connect several providers in one session. Default `false`.                                                                          |
| `connected_uids`            | string\[] | Terra `user_id`s already connected for this end user; their providers show as connected with a disconnect option. Unknown IDs return a `400`.                                                                |
| `bypass_feedback`           | boolean   | Set `false` to keep the user on the widget's own result screen instead of redirecting them to your URL immediately.                                                                                          |
| `sdk_app`                   | string    | Set to `"grip"` to send Apple Health, Health Connect and Samsung Health connections to [Terra Grip](/mobile-sdks/terra-grip-companion-app), for users without your own app. Any other value returns a `400`. |
| `use_terra_avengers_app`    | boolean   | Allow Apple Health connections through the Terra mobile app. Default `false`.                                                                                                                                |
| `apple_app_url`             | string    | URL of your own iOS app to hand Apple Health connections to, instead of the Terra mobile app.                                                                                                                |
| `samsung_app_url`           | string    | URL of your own Android app to hand Samsung Health connections to.                                                                                                                                           |

The widget is shown in the end user's own language, negotiated from their browser's `Accept-Language` header (English fallback). There is nothing to set on the request.

## Read the widget URL

A successful call returns `201` with the **widget URL** in the `"url"` field.

{% code title="JSON" lineNumbers="true" %}

```json
{
  "session_id": "23dc2540-7139-44c6-8158-f81196e2cf2e",
  "url": "https://access.tryterra.co/widget/session/23dc2540-7139-44c6-8158-f81196e2cf2e",
  "status": "success",
  "expires_in": 86400
}
```

{% endcode %}

The URL is valid for `expires_in` seconds (24 hours). Create a fresh session each time a user starts the connect flow rather than storing URLs.

| Status | Meaning                                                                                                                         |
| ------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `201`  | Session created; `url` is ready to open.                                                                                        |
| `400`  | A field is malformed. `message` explains which; `invalid_user_ids` lists any `connected_uids` that do not exist.                |
| other  | `status` is `"error"` and `message` explains why. Most often the `dev-id` / `x-api-key` pair is not valid for this environment. |

## Open the widget URL

Pass the `"url"` to your client side and open it in:

* an **in-app browser**, if using a mobile app,
* or a **new tab**, if using a web app.

Your [end user](https://docs.tryterra.co/introduction/core-concepts#end-users-and-reference-ids) picks a provider, logs in, grants permissions, and is sent to your `auth_success_redirect_url` with their Terra `user_id` and your `reference_id` as query parameters. At the same time, an authentication event is sent to your destination: see [Handle the auth event](/unified-api/authentication-flow#handle-the-auth-event).

{% hint style="info" %}
**Make it yours.** The widget's name, logo and colours are set in your Terra Dashboard under **Authentication**, where you can also preview the widget and test a connection before shipping. The permissions list can be [customised through your Terra Dashboard](/unified-api/setting-up-data-sources#choose-data-types) too.
{% endhint %}

You can find a list of all your **authenticated users** in:

* Your [Terra Dashboard > Users](https://dashboard.tryterra.co/dashboard/users)
* Or by using [`GET /subscriptions`](https://docs.tryterra.co/reference/health-and-fitness-api/user#get-subscriptions)

## Avoid common mistakes

{% hint style="danger" %}

* Do not expose your API credentials. Always create the widget session from your **backend**.
* Do not call the API from your **frontend**, as this will lead to a **CORS error**.
* Do not use **WebView** or **iFrame** for the authentication flow. Using them poses security risks due to the invisible URL bar, meaning that the user cannot know the domain onto which they are entering their username & password. Providers may completely block authentication leading to an error during the flow. Instead, use a **new tab** or an **in-app browser** to open the URL.
* Do not reuse widget URLs across users or sessions. Each `url` belongs to one `reference_id`; create a new session per connect attempt.
  {% endhint %}

## Migrate from `/auth/generateWidgetSession`

Existing integrations keep working today, and the legacy endpoint is planned for deprecation on 3 November 2026. Accounts created after 3 September 2026 cannot use it at all. If you want the redesigned widget, the changes are small:

| Legacy (`/v2/auth/generateWidgetSession`)                    | Redesigned widget (`/api/widget/session`)                                                                              |
| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `POST https://api.tryterra.co/v2/auth/generateWidgetSession` | `POST https://access.tryterra.co/api/widget/session`, with the same `dev-id` / `x-api-key` headers.                    |
| `"language": "en"` in the body                               | Remove it. The widget follows the end user's browser language automatically.                                           |
| `"providers": "multi-auth"`                                  | Send `"multi_auth": true` instead, alongside your `providers` list.                                                    |
| `"providers": "ALL"`                                         | Omit `providers`. The widget then shows exactly the data sources you have enabled in your Dashboard.                   |
| Response `expires_in: 900`                                   | Response `expires_in: 86400`. Otherwise the response shape (`session_id`, `url`, `status`, `expires_in`) is unchanged. |
| Widget styled from the legacy dashboard settings             | Styled from **Dashboard > Authentication**. Your name and logo carry over; bespoke legacy themes do not.               |

Everything else works the same way: `reference_id`, redirect URLs, `show_disconnect`, `connected_uids`, `use_terra_avengers_app`, and the authentication events you receive.

## Legacy endpoint

{% hint style="warning" %}
`POST /auth/generateWidgetSession` is deprecated, with deprecation planned for **3 November 2026**. Existing apps keep working, and we will give notice well before any breaking change. Accounts created after 3 September 2026 get a `410` error pointing to `POST https://access.tryterra.co/api/widget/session`.
{% endhint %}

Call [`/auth/generateWidgetSession`](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-generatewidgetsession) from your backend:

```bash
curl --request POST --url https://api.tryterra.co/v2/auth/generateWidgetSession \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
      "language": "en",
      "reference_id": "my_first_connection",
      "auth_success_redirect_url": "https://example.com/success",
      "auth_failure_redirect_url": "https://example.com/failure"
  }'
```

The response has the same shape as the redesigned widget, with the URL on `widget.tryterra.co` and `expires_in` of `900` seconds:

```json
{
   "session_id": "23dc2540-7139-44c6-8158-f81196e2cf2e",
   "url": "https://widget.tryterra.co/session/344d475f-296a-489a-a88c-54183671dafd",
   "status": "success",
   "expires_in": 900
}
```

Open the `url` the same way: a new tab, or an in-app browser on mobile.

## Next steps

* [Authentication redirect pages](/unified-api/customising-authentication-redirects): send the end user back to your app after they connect.
* [Handle the auth event](/unified-api/authentication-flow#handle-the-auth-event): store the `user_id` Terra sends when the connection succeeds.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra sends for connected users.


# Custom authentication UI

Build your own connect buttons, generate a provider login link from your backend, and open it for the end user.

Use your own UI instead of the Terra widget when you want a button per provider inside your app. Your backend generates a login link for one provider, and the end user goes straight to that provider's login screen.

## Build your UI

First, create a **button** for each data source that a user might want to connect. (e.g. a "Connect to Fitbit" button). You may take inspiration from the Terra Widget when creating your own UI.

You may use the [/integrations/detailed](https://docs.tryterra.co/reference/health-and-fitness-api/integrations#get-integrations-detailed) endpoint to fetch metadata for each source available through Terra when creating your UI. This enables you to dynamically retrieve the sources you’ve [activated in your Dashboard](/unified-api/setting-up-data-sources) (using the `enabled` boolean parameter in the response), along with their associated metadata, such as available **data types**, **display names**, and **logos**.

## Generate an auth link

From your backend, call [`/auth/authenticateUser`](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-authenticateuser) to generate an authentication link.

Use the parameter `resource` to pass a source name (e.g. `"oura"` , `"withings"` ..)

{% hint style="info" %}
Apple Health, Health Connect and Samsung Health have no web login. If you have no app of your own, pass `sdk_app: "grip"` to send the user to [Terra Grip](/mobile-sdks/terra-grip-companion-app).
{% endhint %}

{% code title="Command Line" %}

```bash
curl --request POST --url https://api.tryterra.co/v2/auth/authenticateUser?resource=oura \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
      "reference_id": "my_first_connection",
      "auth_success_redirect_url": "https://example.com/success",
      "auth_failure_redirect_url": "https://example.com/failure"
  }'
```

{% endcode %}

See the [API reference](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-authenticateuser) for every parameter.

{% hint style="info" %}
Use `reference_id` in your request Body to pass in your own end user's ID on your system.

This will simplify reconciling the terra [User](https://docs.tryterra.co/introduction/core-concepts#users) with your end user.
{% endhint %}

## Read the auth URL

The endpoint will generate an **authentication url** in the response. Retrieve it by parsing `"auth_url"`.

{% code title="JSON" lineNumbers="true" %}

```json
{
  "status": "success",
  "user_id": "23dc2540-7139-44c6-8158-f81196e2cf2e",
  "auth_url": "https://cloud.ouraring.com/oauth/authorize?response_type=code&client_id=...&redirect_uri=https%3A%2F%2Fapi.tryterra.co%2Fv2%2Fauth%2Foura%2Foauth2&scope=email+spo2+session+heartrate+personal+daily+workout+tag.."
}
```

{% endcode %}

## Open the auth URL

Pass the retrieved `"auth_url"` to your client side, and open it either in:

* an **in-app browser**, if using a mobile app,
* or a **new tab**, if using a web app

This will take the user straight to the [data source's](https://docs.tryterra.co/introduction/core-concepts#sources) login screen so they can connect it.

<div><figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FTuSK9MXKw4AOlEQWhIWb%2Fscreenshot%20(2).png?alt=media&amp;token=7ed5038d-471a-4ed7-9818-ea18bb722364" alt="" width="182"><figcaption><p><strong>Login</strong> Screen<br>(example: Oura)</p></figcaption></figure> <figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2F1lAow8Zfl010xLxwpRUI%2Fscreenshot%20(3).png?alt=media&amp;token=36da4b9e-bd6d-495f-b0bb-bf70302d8574" alt="" width="182"><figcaption><p><strong>Permission</strong> screen<br>(example: Oura)</p></figcaption></figure></div>

{% hint style="info" %}
The permissions list can be [customised through your Terra Dashboard](/unified-api/setting-up-data-sources#choose-data-types)
{% endhint %}

## Avoid common mistakes

{% hint style="danger" %}

* Do not expose your API credentials. Instead, always call the [`/auth`](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-authenticateuser) endpoints from your **backend.**
* Do not call the API from your **frontend**, as this will lead to a **CORS error.**
* Do not use **WebView** or **iFrame** for the authentication flow. Using them poses security risks due to the invisible URL bar, meaning that the user cannot know the domain onto which they are entering their username & password. Providers may completely block authentication leading to an error during the flow. Instead, use a **new tab** or an **in-app browser** to open the URL returned by the `/auth` endpoints.
  {% endhint %}

## Next steps

* [Authentication redirect pages](/unified-api/customising-authentication-redirects): send the end user back to your app after they connect.
* [Handle the auth event](/unified-api/authentication-flow#handle-the-auth-event): store the `user_id` Terra sends when the connection succeeds.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra sends for connected users.


# Authentication redirect pages

Set where Terra sends the end user after they connect a provider, and read the parameters added to that URL.

After the end user completes the authentication flow, they are redirected to a default final URL: a success or failure screen, before they go back to your app. You can replace these URLs when you call one of the `/auth` endpoints.

## Default redirect pages

When the user authenticates a health account (e.g. Oura), before they go back to your app, they see a final URL (screen) of the authentication flow, which is either a success or failure screen.

<div align="center"><figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-dca5241cf04f5656798ab3e8118199177222a7c9%2FCapture%20d%E2%80%99%C3%A9cran%202025-03-28%20%C3%A0%2021.17.40.png?alt=media" alt="" width="188"><figcaption><p>Default <strong>Success</strong> Redirect URL</p></figcaption></figure> <figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-d27d18585346ec99b902080bc799619bcdb3176a%2FCapture%20d%E2%80%99%C3%A9cran%202025-03-28%20%C3%A0%2021.13.32.png?alt=media" alt="" width="188"><figcaption><p>Default <strong>Failure</strong> Redirect URL</p></figcaption></figure></div>

The final url will append the following parameters:

* `user_id` (not Null)
* `resource` (not Null)
* `reference_id` (can be Null if you did not pass it in the auth endpoint).

{% code title="Success Auth URL (Example)" %}

```url
https://widget.tryterra.co/session/demo/success?user_id=bc205b50-dabe-4680-9d35-38517b915dc1&resource=GOOGLE&reference_id=null
```

{% endcode %}

## Set your redirect URLs

Terra provides these urls by default, and they can also be customized in the `/auth` endpoints. They can be specified in the **body** of the authentication request as:

* `auth_success_redirect_url`
* `auth_failure_redirect_url`

## Redirect targets

You can redirect to a:

* **Web page:** A specific page on your web application, including any useful query parameters.
  * Example: `https://somereallycoolcompany.com?terra_auth_success=true`
* **Deep link:** A deep link into your mobile application.
  * Example: `reallycoolapp://success`

### Mobile-only sources

{% hint style="warning" %}

* When using the widget, when the user selects one of the [Mobile SDK-based integrations](/mobile-sdks/mobile-only-sources) (e.g. Apple Health, Samsung Health, Health Connect), they will by default be redirected to the `auth_success_redirect_url` with a **null** `user_id`.
* This Redirect URL can be used to redirect your end-user to your mobile app instead so that they complete the connection flow to the Mobile-only integrations using **Deep Links.**
  {% endhint %}

## Next steps

* [Event delivery](/destinations/events): how Terra sends events to your destinations, and what their statuses mean.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra sends for connected users.
* [Mobile SDKs](/mobile-sdks/mobile-only-sources): connect Apple Health, Samsung Health and Health Connect from your app.


# Health data events

Handle the data events Terra sends to your destination when a connected user's data syncs.

Once you connect a user, Terra refreshes their tokens, tracks authentication updates, and sends their health and fitness data to your destination as soon as it is available. You only need to request data to backfill history, to debug, or as a fallback.

## Before you begin

* Get your **API key** from the [Terra dashboard](https://dashboard.tryterra.co/).
* [Set up a destination](/destinations/setting-up-data-destinations) where Terra sends events.
* [Enable the data sources](/unified-api/setting-up-data-sources) your app needs (e.g., oura, garmin, etc).
* [Connect at least one user](/unified-api/authentication-flow), and [handle the auth event](/unified-api/authentication-flow#handle-the-auth-event). If you have no connected user yet, use the [Data generator](https://dashboard.tryterra.co/dashboard/generate) to send test data to your destination.

## Data event types

When a connected [user](https://docs.tryterra.co/introduction/core-concepts#users) has new data at their provider, Terra sends a data event to your [destination](/introduction/core-concepts#destinations). [Event delivery](/destinations/events) explains how Terra delivers and retries it.

The event's `type` is its data type:

| Type           | Holds                                                                                                              |
| -------------- | ------------------------------------------------------------------------------------------------------------------ |
| `activity`     | One tracked workout with a start and end time, such as a 5k run between pressing start and stop.                   |
| `sleep`        | One sleep session. It can include time in bed while awake, if the wearable records it.                             |
| `daily`        | The running total for one day so far, such as steps and calories. Use only the date part of `metadata.start_time`. |
| `body`         | Body metrics for one day, such as weight or blood glucose.                                                         |
| `nutrition`    | The food logged in one day.                                                                                        |
| `menstruation` | One day of the menstrual cycle: phase, flow and anything logged.                                                   |
| `athlete`      | The end user's profile on the provider.                                                                            |
| `hormone`      | One hormone test result.                                                                                           |

The [event types reference](https://docs.tryterra.co/reference/health-and-fitness-api/event-types#data-events) lists every type with its format, and the [data models](https://docs.tryterra.co/reference/health-and-fitness-api/data-models) give every field.

You can find all your received events (payloads) in your [Terra Dashboard > Events](https://dashboard.tryterra.co/dashboard/debug).

{% hint style="warning" %}
The same payload can arrive again with more data. Each new copy is a superset of the last, so overwrite your stored record instead of adding a new one. Match the two by the payload's unique key, listed in [uniquely identifying payloads](https://docs.tryterra.co/reference/health-and-fitness-api/data-models#uniquely-identifying-payloads).
{% endhint %}

### Example payload

Data Events will take the following form:

{% code title="ActivityPayload.json" lineNumbers="true" %}

```json
{
    "type": "activity",
    "data": [
        {
          "metadata": {
                "type": 45,
                "start_time": "2024-10-03T18:17:45.000000+08:00",
                "city": null,
                "name": "MEDITATION",
                "state": null,
                "upload_type": 1,
                "country": null,
                "summary_id": "f09554ca56fde426de5d7f9c34fc0e1e3ff015c2ae253b39",
                "end_time": "2024-10-03T18:38:39.000000+08:00"
          },
          ..... ommitted for brevity
        }
    ],
    "user": {
        "reference_id": "2397",
        "active": true,
        "user_id": "9d5dc9eb-3e02-4b37-9a7b-b14b5a5a2b93",
        "last_webhook_update": "2024-10-03T11:13:43.360227+00:00",
        "created_at": null,
        "scopes": "fitness.sleep.read,fitness.body.read,fitness.body_temperature.read,fitness.activity.read,fitness.blood_pressure.read,fitness.location.read,calendar.settings.readonly,fitness.reproductive_health.read,userinfo.email,user.birthday.read,user.gender.read,fitness.oxygen_saturation.read,fitness.heart_rate.read,userinfo.profile,fitness.nutrition.read,fitness.blood_glucose.read",
        "provider": "GOOGLE"
    },
    "version": "2022-03-16"
}
```

{% endcode %}

## Test your destination

For testing out the different event types mentioned above, you may also use [the payload simulator](https://dashboard.tryterra.co/dashboard/generate) in the Terra Dashboard. See the tutorial below for a step by step guide.

{% embed url="<https://app.arcade.software/share/U79B7Z7lfR85jSKUIIVF>" %}

{% prompt description="Resend an event to test your webhook handler" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Resend the most recent sleep event for user 8f2a1c to my webhook so I can test my handler.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## Check your setup

1. **Set up**: Have you tested that your destination can receive data payloads from Terra?
2. **Connect a user**: Have you connected a user via Terra? Have you received an Authentication Event?
3. **Receive data**: After completing an event (e.g. activity), did you receive a Data Event "Activity"?

If you didn't receive an expected payload after a long time, see [Troubleshooting](/unified-api/debugging-faq) to check the user's data is synced properly.

## Next steps

* [Historical data requests](/unified-api/requesting-historical-data): backfill data from before the user connected.
* [Writing data to providers](/unified-api/write-data): send planned workouts back to a user's provider.
* [Troubleshooting](/unified-api/debugging-faq): find out why an expected event did not arrive.


# Historical data requests

Request a user's past data from the Unified API, either to your destination or in the response.

Terra is event-based: new and ongoing data reaches your destination (e.g. webhook, database, or cloud storage bucket) without any requests from you. To get data from before a user connected, request it from the Unified API endpoints by user ID, data type and time range.

## Before you begin

* Get your **API key** and **dev ID** from the [Terra dashboard](https://dashboard.tryterra.co/).
* [Set up a destination](/destinations/setting-up-data-destinations) where Terra sends event and data updates.
* [Enable the data sources](/unified-api/setting-up-data-sources) your app requires.
* [Connect at least one user](/unified-api/authentication-flow) through the Unified API. Requests take that user's `user_id` and at least a start date.

## When to request historical data

### When a user first connects

When an end user first connects an account (e.g. wearable, device, health app), you will by default only receive data from that point onwards.

If you would like to **build a historical health & fitness profile of the user,** to establish **baselines** for statistics, or for any other calculations, you can make a request to Terra for data from prior to the user's authentication.

{% hint style="info" %}
**Time range limits**

Some [providers](/unified-api/setting-up-data-sources) impose limits on how far back a developer can request data. Those are:

* **Garmin**: Garmin sets how far back history goes for each Garmin app. History is only available for users who enabled Garmin's historical data permission.
* **Polar**: workouts go back 30 days into the past, but not prior to the moment the user granted permission. Sleep and daily data go back about a year, including from before the user granted permission.
* **Coros:** 3 months into the past, from the current point in time, or 24 hours prior to the user's authentication. Whichever of the two limits gets hit first gets applied
* **Health Connect**: 30 days into the past, but not prior to the moment the user granted permission.
  {% endhint %}

### As a refresh fallback

As a **fallback**, you should implement a "pull down to refresh" functionality or alternative (like a sync now button, etc...).

Hitting this button should trigger a data pull of the last e.g. 14 days of data for the user, for all the data types you ingest.

## Request data from the dashboard

You may want your customer support team to use the Terra dashboard to debug by re-sending data, or verifying whether or not Terra fetches the data correctly. See the guide below for a step by step tutorial on how to do so.

{% embed url="<https://app.guideflow.com/player/dr96elwaor>" %}

## Request data from the API

To request historical data from your **backend**, call one of the [Data Retrieval Endpoints](https://docs.tryterra.co/reference#historical-data-retrieval). Refer to the [API endpoints](https://docs.tryterra.co/reference) section for further details on usage.

{% prompt description="Pull a user's historical data without sending it to your webhook" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Pull the last 30 days of sleep and daily data for user 8f2a1c and show me the payload shape, without sending it to my webhook.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

### Request parameters

**Required parameters**

* `user_id`
* `start_date`

**Optional parameters**

Terra's Data Retrieval endpoints include many other useful and important parameters.

1. `with_samples` must be set to `true` to receive granular data (see [Choose data types](/unified-api/setting-up-data-sources#choose-data-types)).
2. `to_webhook` must be set to `true` if you want to receive data asynchronously to your Destination. For synchronous data retrieval (if your use case is time-sensitive), just set this parameter to `false`. It defaults to `true` if not provided.
3. `end_date` is exclusive on these endpoints. Data is returned up to but not including this date, so pass the day after the last day you want.

{% hint style="info" %}
**Handling asynchronous data retrievals**

When making a `to_webhook=true` request, keep track of the value of the `terra-reference` header. When the event is eventually sent to your webhook, the event's `terra-reference` will match that of the initial request, allowing you to mark off the data transfer as successfully completed
{% endhint %}

### Example: backfill after a user connects

Taking **Python FastAPI** as an example framework, you may set up your server code to look like the following:

{% code title="Python" lineNumbers="true" %}

```python
@app.post("/webhook")
async def webhook_handler(request: Request):
    payload = await request.json()
    
    if payload.get("type") == "auth" and payload.get("status") == "success":
        # Calculate date range, to get data from 28 days ago to today
        start_date = (datetime.utcnow() - timedelta(days=28)).strftime('%Y-%m-%d')
        end_date = (datetime.utcnow() + timedelta(days=1)).strftime('%Y-%m-%d')
        headers = {
            "x-api-key": os.getenv("TERRA_API_KEY"), 
            "dev-id": os.getenv("TERRA_DEVELOPER_ID")
        }
        endpoints = [
            "/activity", 
            "/daily", 
            "/sleep", 
            "/body"
        ]

        # Fetch data from each endpoint
        results = {}
        for endpoint in endpoints:
            try:
                response = requests.get(
                    f"{TERRA_API_URL}{endpoint}", 
                    headers=headers, 
                    params={
                        "start_date": start_date, 
                        "end_date": end_date,
                        "to_webhook": True
                        }
                    )
                response.raise_for_status()
                results[endpoint] = response.json()
            except requests.HTTPError as e:
                raise HTTPException(status_code=response.status_code, detail=f"Error fetching data from {endpoint}")

        return {"message": "Data fetched successfully", "data": results}
    
    return {"message": "Webhook type or status did not match criteria"}
```

{% endcode %}

## Request longer time ranges

Time ranges longer than one month must use `to_webhook=true`, and Terra sends the data **asynchronously**. The same request with `to_webhook=false` returns a `400`. This is due to the large amounts of data being transferred, which would hang the request making/handling process for >30 seconds.

Following a large request, you will receive the following:

1. **"Large request processing" event**: you will immediately receive a [https://docs.tryterra.co/reference/health-and-fitness-api/event-types#large-request-processing](https://docs.tryterra.co/reference/health-and-fitness-api/event-types#large-request-processing "mention") event. This indicates that Terra has acknowledged the large request and is currently processing the data retrieval from the [Provider](https://docs.tryterra.co/introduction/core-concepts#sources).
2. **"Large request sending" event**: once data retrieval has finished, Terra will organise the data into chunks, and send a [https://docs.tryterra.co/reference/health-and-fitness-api/event-types#large-request-sending](https://docs.tryterra.co/reference/health-and-fitness-api/event-types#large-request-sending "mention") payload, indicating **the number of payloads to expect.**
3. **Chunks**: Terra sends the data to you in chunks of at most 10MB each.
4. **Header**: all chunks contain the **same** `terra-reference` header value. Once the number of payloads indicated with the same `terra-reference` header value have been received, you can consider the data transfer request complete.

## Next steps

* [Writing data to providers](/unified-api/write-data): send planned workouts back to a user's provider.
* [Event delivery](/destinations/events): track deliveries, retries and resends of the data you requested.
* [Troubleshooting](/unified-api/debugging-faq): find out why requested data did not arrive.


# Writing data to providers

Learn how to write data back to providers, and create a bi-directional data stream between your app and the various integrations you connect to

Terra allows you to write data back to a user's account, wherever supported by the respective [Provider](https://docs.tryterra.co/introduction/core-concepts#sources).

## Writing Planned Workouts

### Overview

Writing planned workouts allows you to create a workout plan for the user (such as those [commonly used with Zwift](https://whatsonzwift.com/workouts))

This will typically look like the following example:

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FxJoiJ7sMVlZyTUtwrcd4%2Fimage.png?alt=media&amp;token=4e954c5d-2dab-4bac-918f-a519e50b2340" alt=""><figcaption><p>Example workout from <a href="https://whatsonzwift.com/workouts/baby-on-board">https://whatsonzwift.com/workouts/baby-on-board</a></p></figcaption></figure>

Planned workouts consist of a **series of steps**. Each step has:

* **Completion criteria** (called **duration** for all intents and purposes). For example:
  * distance (keep going until you cover 500m),
  * energy expenditure (keep going until you burn 200 kcal)
  * heart rate threshold (keep going until your heart rate reaches above 150 bpm)
  * etc..
* One or more **targets** to be maintained
  * heart rate (maintain heart rate between certain bounds)
  * speed (maintain speed between certain bounds)
  * grade (inclination above a certain threshold)
  * etc...
* An associated **intensity** label
  * Warmup
  * Active
  * Cooldown
  * etc..
* An **exercise type**
  * Running
  * Cycling
  * Deadlifting
  * etc...
* A series of sub-steps

These modalities allow any workout to be described in a series of defined steps for each of its segments.

Once written, a planned workout will be available in the user's library of workouts on the respective platform, and the user will then be able to follow the workout step by step on their wearable device

## Writing Planned Workouts

### Supported providers

Currently supported [providers](https://docs.tryterra.co/unified-api/supported-integrations) are:

* Garmin
* Hammerhead
* Coros
* TodaysPlan

See the [https://docs.tryterra.co/unified-api/supported-integrations](https://docs.tryterra.co/unified-api/supported-integrations "mention") page for a full list of supported data types per [Provider](https://docs.tryterra.co/introduction/core-concepts#sources)

### Usage

In order to write a planned workout to the user's device, you may use the following endpoint

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>" path="/plannedWorkout" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>
{% endopenapi %}

The response will include `log_ids` which will be a list of the identifiers for the uploaded workout plans. You may use those identifiers to identify the workout plan later on in the [https://docs.tryterra.co/reference/health-and-fitness-api/workouts](https://docs.tryterra.co/reference/health-and-fitness-api/workouts "mention")endpoint, or to delete them using the [https://docs.tryterra.co/reference/health-and-fitness-api/workouts](https://docs.tryterra.co/reference/health-and-fitness-api/workouts "mention")

### Enum values

The `steps`, `durations`, and `targets` objects use integer enums. The accepted values are below. Not every provider supports every value. Garmin accepts `target_type` values 0, 1, 2, 3, 4, 8, 11, 13, 14 and 15 only; a step whose targets fall entirely outside that set is rejected.

**Step `type`**

| Value | Meaning     |
| ----- | ----------- |
| 0     | Step        |
| 1     | Repeat step |

**Step `intensity`**

| Value | Meaning   |
| ----- | --------- |
| 0     | Rest      |
| 1     | Warm up   |
| 2     | Cool down |
| 3     | Recovery  |
| 4     | Interval  |
| 5     | Active    |

**`duration_type`**

| Value | Meaning           |
| ----- | ----------------- |
| 0     | Time              |
| 1     | Distance (metres) |
| 2     | Heart rate below  |
| 3     | Heart rate above  |
| 4     | Calories          |
| 5     | Open              |
| 6     | Power below       |
| 7     | Power above       |
| 8     | Repetition time   |
| 9     | Reps              |
| 10    | Fixed rest        |
| 11    | Time at valid CdA |
| 12    | Steps             |

**`target_type`**

| Value | Meaning                |
| ----- | ---------------------- |
| 0     | Speed                  |
| 1     | Heart rate             |
| 2     | Open                   |
| 3     | Cadence                |
| 4     | Power                  |
| 5     | Grade                  |
| 6     | Resistance             |
| 7     | Power lap              |
| 8     | Swim stroke            |
| 9     | Speed lap              |
| 10    | Heart rate lap         |
| 11    | Pace                   |
| 12    | Heart rate threshold % |
| 13    | Heart rate max %       |
| 14    | Speed %                |
| 15    | Power %                |
| 16    | Repetition             |
| 17    | TSS                    |
| 18    | IF                     |
| 19    | RPE                    |

### Examples

#### Aerobic fitness test

The aerobic fitness test begins with a 5 minute warm-up.

After warming up, the intensity will ramp up over the duration of 5 minutes, reaching a 91% max HR intensity.

Once you are done with the all out effort, you will spend 2 minutes in a recovery step, before spending 5 minutes cooling down

{% tabs %}
{% tab title="General" %}

```json5
{
    "data": [
        {
            "steps": [
                {
                    "type": 1,
                    "order": 0,
                    "description": "Warm Up BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Warm Up",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 300
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 70.0,
                                    "hr_percentage_low": 60.0,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Warm Up RAMP_UP",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 1",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 79.5,
                                    "hr_percentage_low": 79.5,
                                    "hr_percentage": 79.5
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 70.0,
                                    "hr_percentage_low": 70.0,
                                    "hr_percentage": 70.0
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 65,
                                    "power_percentage_low": 65,
                                    "power_percentage": 65
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 95.0,
                                    "cadence_low": 85.0,
                                    "cadence": null
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 2",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 85.8,
                                    "hr_percentage_low": 85.8,
                                    "hr_percentage": 85.8
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 76.0,
                                    "hr_percentage_low": 76.0,
                                    "hr_percentage": 76.0
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 75,
                                    "power_percentage_low": 75,
                                    "power_percentage": 75
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 95.0,
                                    "cadence_low": 85.0,
                                    "cadence": null
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 3",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 91.6,
                                    "hr_percentage_low": 91.6,
                                    "hr_percentage": 91.6
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 82.0,
                                    "hr_percentage_low": 82.0,
                                    "hr_percentage": 82.0
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 85,
                                    "power_percentage_low": 85,
                                    "power_percentage": 85
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 95.0,
                                    "cadence_low": 85.0,
                                    "cadence": null
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 4",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 96.7,
                                    "hr_percentage_low": 96.7,
                                    "hr_percentage": 96.7
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 87.0,
                                    "hr_percentage_low": 87.0,
                                    "hr_percentage": 87.0
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 95,
                                    "power_percentage_low": 95,
                                    "power_percentage": 95
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 95.0,
                                    "cadence_low": 85.0,
                                    "cadence": null
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 5",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 101.4,
                                    "hr_percentage_low": 101.4,
                                    "hr_percentage": 101.4
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 91.0,
                                    "hr_percentage_low": 91.0,
                                    "hr_percentage": 91.0
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 105,
                                    "power_percentage_low": 105,
                                    "power_percentage": 105
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 95.0,
                                    "cadence_low": 85.0,
                                    "cadence": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 120
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 76.0,
                                    "hr_percentage_low": 69.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 67.0,
                                    "hr_percentage_low": 60.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 60,
                                    "power_percentage_low": 50,
                                    "power_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Main Session BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Sprint",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 8
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 106.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 98.5,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": null,
                                    "power_percentage_low": 200,
                                    "power_percentage": null
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 120.0,
                                    "cadence_low": 100.0,
                                    "cadence": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 180
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 73.0,
                                    "hr_percentage_low": 65.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63.0,
                                    "hr_percentage_low": 57.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 55,
                                    "power_percentage_low": 45,
                                    "power_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Main Session BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Sprint",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 8
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 106.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 98.5,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": null,
                                    "power_percentage_low": 200,
                                    "power_percentage": null
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 120.0,
                                    "cadence_low": 100.0,
                                    "cadence": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 300
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 73.0,
                                    "hr_percentage_low": 65.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63.0,
                                    "hr_percentage_low": 57.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 55,
                                    "power_percentage_low": 45,
                                    "power_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Main Session BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Aerobic Test",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 480
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 106.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 98.5,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": null,
                                    "power_percentage_low": 98,
                                    "power_percentage": null
                                },
                                {
                                    "target_type": 3,
                                    "cadence_high": 110.0,
                                    "cadence_low": 90.0,
                                    "cadence": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 120
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 73.0,
                                    "hr_percentage_low": 65.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63.0,
                                    "hr_percentage_low": 57.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 55,
                                    "power_percentage_low": 45,
                                    "power_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Cool Down BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Cool Down",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 300
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 12,
                                    "hr_percentage_high": 73.0,
                                    "hr_percentage_low": 69.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63.0,
                                    "hr_percentage_low": 60.0,
                                    "hr_percentage": null
                                },
                                {
                                    "target_type": 15,
                                    "power_percentage_high": 55,
                                    "power_percentage_low": 50,
                                    "power_percentage": null
                                }
                            ]
                        }
                    ]
                }
            ],
            "metadata": {
                "type": 1,
                "name": "Aerobic Fitness Test",
                "description": "The aerobic fitness test begins with a warm-up. After warming up, you will be required to complete two maximal sprints. Once you are done with the sprints, you will have to undergo a 9-minute all-out test. During the test, it is important to pace yourself and give your best effort, sustaining it for the entire duration of 8 minutes.",
                "provider": "COROS",
                "planned_date": "2025-01-29",
                "estimated_duration_seconds": 2100
            }
        }
    ]
}
```

{% endtab %}

{% tab title="Adapted to Garmin" %}

```json
{
    "data": [
        {
            "steps": [
                {
                    "type": 1,
                    "order": 0,
                    "description": "Warm Up BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Warm Up",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 300
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 70,
                                    "hr_percentage_low": 60,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Warm Up RAMP_UP",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 1",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 70,
                                    "hr_percentage_low": 70,
                                    "hr_percentage": 70
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 2",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 76,
                                    "hr_percentage_low": 76,
                                    "hr_percentage": 76
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 3",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 82,
                                    "hr_percentage_low": 82,
                                    "hr_percentage": 82
                                }
                            ]
                        },
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Ramp Up 4",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 60
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 87,
                                    "hr_percentage_low": 87,
                                    "hr_percentage": 87
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 120
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 67,
                                    "hr_percentage_low": 60,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Main Session BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Sprint",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 8
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 98.5,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 180
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63,
                                    "hr_percentage_low": 57,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Main Session BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Sprint",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 8
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 98.5,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 300
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63,
                                    "hr_percentage_low": 57,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Main Session BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Aerobic Test",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 480
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": null,
                                    "hr_percentage_low": 98.5,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Recovery BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Recovery",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 120
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 63,
                                    "hr_percentage_low": 57,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                },
                {
                    "type": 1,
                    "order": 0,
                    "description": "Cool Down BASIC",
                    "durations": [
                        {
                            "duration_type": 9,
                            "reps": 1
                        }
                    ],
                    "steps": [
                        {
                            "type": 0,
                            "order": 0,
                            "intensity": 5,
                            "description": "Cool Down",
                            "durations": [
                                {
                                    "duration_type": 0,
                                    "seconds": 300
                                }
                            ],
                            "targets": [
                                {
                                    "target_type": 13,
                                    "hr_percentage_high": 73,
                                    "hr_percentage_low": 69,
                                    "hr_percentage": null
                                }
                            ]
                        }
                    ]
                }
            ],
            "metadata": {
                "type": 1,
                "name": "Aerobic Fitness Test",
                "description": "The aerobic fitness test begins with a warm-up. After warming up, you will be required to complete two maximal sprints. Once you are done with the sprints, you will have to undergo a 9-minute all-out test. During the test, it is important to pace yourself and give your best effort, sustaining it for the entire duration of 8 minutes.",
                "provider": "GARMIN",
                "planned_date": "2025-01-29",
                "estimated_duration_seconds": 2100
            }
        }
    ]
}
```

{% endtab %}
{% endtabs %}


# Dedicated source API keys

Set up your own developer credentials for Strava, Virtuagym, Huawei and Samsung Health instead of using Terra's managed keys.

Terra manages the API keys of data sources, so you can connect users without applying for each key yourself. This page covers how to set up your own access keys for the sources that support them.

For some data sources, you may choose to have your own access keys for different reasons:

1. **Required by the provider:** the provider requires in their terms that you use dedicated access keys.
2. **Preferred by you:** you simply wish to avoid rate limits and separate your environment from the managed Terra keys.

You can find the list of providers that support this in the [integrations table](https://docs.tryterra.co/unified-api/supported-integrations#integrations-list), marked as `Managed`. The table also lists each provider's developer dashboard.

## Strava

1. Log in to <https://strava.com/settings/api> and create an application. Save its client ID and client secret.
2. In your Terra dashboard, open **Connections**, choose **Strava** and follow the setup. It walks you through your custom domain and then shows the Authorization Callback Domain to enter in your Strava application.
3. Enter the client ID and client secret in the dashboard and save. Terra registers the Strava webhook for you.

## Virtuagym

1. Generate an API key from your Virtuagym Professional account, under **System Settings → Business Info → Advanced**. If the option isn't visible, contact Virtuagym support.
2. In your Terra dashboard, add Virtuagym to your connections under API > Connections > Add more.
3. After adding Virtuagym, go to the Virtuagym options.
4. Fill your portal name in the client ID, and your API key in the client secret.

## Huawei

### Create a Huawei ID

Follow the [Registration & Verification guide](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148).

{% hint style="info" %}
**Identity verification**

Through the Huawei ID registration process, you will be asked to verify your identity.

* If you own a business, follow the guide for [DUNS number verification](https://developer.huawei.com/consumer/en/doc/start/atpopb-0000001062836624) or the guide [using a Business License](https://developer.huawei.com/consumer/en/doc/start/mracoei-0000001062678404).
* If you are an individual developer, follow [this guide](https://developer.huawei.com/consumer/en/doc/start/ibca-0000001062388135) using your personal documents.
  {% endhint %}

### Apply for the HUAWEI ID Service

This is separate from the Huawei ID registration: the *service* is what lets you access the Huawei APIs. Follow the guide [here](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-id-0000001050069756) for a step-by-step explanation.

Use these parameters:

<table><thead><tr><th width="181.591796875">Name</th><th width="490.4951171875">Value</th></tr></thead><tbody><tr><td><strong>Redirect URL</strong></td><td><a href="https://api.tryterra.co/v2/auth/huawei/oauth2">https://api.tryterra.co/v2/auth/huawei/oauth2</a></td></tr><tr><td><strong>App access URL</strong></td><td><a href="https://api.tryterra.co/">https://api.tryterra.co/</a></td></tr><tr><td><strong>Callback address</strong></td><td><a href="https://api.tryterra.co/v2/auth/huawei/oauth2">https://api.tryterra.co/v2/auth/huawei/oauth2</a></td></tr></tbody></table>

### Apply for Huawei Health Kit access

1. Follow the [Health Kit access guide](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-kitservice-0000001050071707) for an in-depth explanation of how to gain access to users' health data through Huawei Health Kit.
2. Register for notifications (webhooks) by following [these steps](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/subscription-0000001078496860#section38652513104):

![](https://files.readme.io/c6f3b5d-image.png)

## Samsung Health

The Android SDK can read Samsung Health's own store directly, through Samsung's Health Data SDK, instead of through Health Connect. Direct access reads every Samsung Health workout, including the ones Samsung Health does not copy into Health Connect.

Samsung approves each app separately, so Terra's access does not cover your app. Apply through the [Samsung Health partnership portal](https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c) with your app's package name and the SHA-256 fingerprint of its signing certificate. Until Samsung approves it, you can read Samsung Health's data through Health Connect.

For the add-on, Samsung's SDK and the code, see [Samsung Health](/mobile-sdks/samsung-health).

## Next steps

* [Per-user OAuth apps](/unified-api/per-user-oauth-apps): let each end user bring their own provider app.
* [Destinations](/destinations/setting-up-data-destinations): choose where Terra sends data.
* [User authentication](/unified-api/authentication-flow): open the widget from your app.


# Per-user OAuth apps

Let each end user connect Strava, Oura or WHOOP through their own OAuth app, and see what they set up at each provider.

Some providers let each of your end users connect through their own OAuth app, instead of through a shared app you manage. This is useful when your users are themselves developers: they register their own app with the provider, and they bring its credentials when they connect through Terra.

## Turn on per-user apps

You enable this per-(provider, dev\_id) from your dashboard: open the connection's settings and turn on **Per-user OAuth apps**, or choose **Enable per-user apps** when you first set the provider up. Once it's on, every new connection for that provider goes through a Terra-hosted page where the user enters their own `client_id` and `client_secret`. Those credentials are pinned to that one connection and aren't shared.

{% hint style="info" %}
**Existing connections aren't affected.** Turning the toggle on changes the routing only for connections created from that point on. Users already connected through your previous setup keep working.
{% endhint %}

The sections below list what each user needs to do at the provider's developer portal. Share the relevant link with your users.

## Strava <a href="#strava" id="strava"></a>

Each user registers their own Strava OAuth app and enters its credentials on the Terra-hosted connect page.

1. Sign in to <https://www.strava.com/settings/api>.
2. Create an application. The **Application Name**, **Website**, and **Application Description** can be anything.
3. Set the **Authorization Callback Domain** to:

   ```
   access.tryterra.co
   ```
4. Save the application. Copy the **Client ID** and **Client Secret**.
5. When prompted on the Terra-hosted connect page, paste the **Client ID** and **Client Secret** to complete the connection.

{% hint style="info" %}
**Callback domain only, no path.** Strava's field accepts a domain, not a full URL. Use exactly `access.tryterra.co`.
{% endhint %}

## Oura <a href="#oura" id="oura"></a>

Each user registers their own Oura OAuth application and enters its credentials on the Terra-hosted connect page.

1. Sign in to <https://cloud.ouraring.com/oauth/applications>.
2. Create a new application. The **Application Name** and **Application Description** can be anything.
3. Set the **Redirect URI** to:

   ```
   https://access.tryterra.co/api/v3/auth/oura/oauth2
   ```
4. Make sure the application is allowed the scopes Terra requests: `email`, `personal`, `daily`, `heartrate`, `workout`, `tag`, `session`, `spo2Daily`.
5. Save the application. Copy the **Client ID** and **Client Secret**.
6. When prompted on the Terra-hosted connect page, paste the **Client ID** and **Client Secret** to complete the connection.

## WHOOP <a href="#whoop" id="whoop"></a>

Each user registers their own WHOOP OAuth application and enters its credentials on the Terra-hosted connect page.

1. Sign in to <https://developer-dashboard.whoop.com/> (a WHOOP account is required).
2. Create a new application.
3. Set the **Redirect URL** to:

   ```
   https://access.tryterra.co/api/v3/auth/whoop/oauth2
   ```
4. Set the **Webhook URL** to:

   ```
   https://api.tryterra.co/v2/hooks/whoop/push
   ```
5. Save the application. Copy the **Client ID** and **Client Secret**.
6. When prompted on the Terra-hosted connect page, paste the **Client ID** and **Client Secret** to complete the connection.

{% hint style="info" %}
**Webhook URL is required.** Without it, real-time updates from WHOOP won't reach Terra and the user's data will only refresh on poll.
{% endhint %}

## Next steps

* [Destinations](/destinations/setting-up-data-destinations): choose where Terra sends data.
* [User authentication](/unified-api/authentication-flow): open the widget from your app.


# Strength training data

Read per-set strength training data, including exercises, sets, reps and load, from the activity payload.

Strength workouts carry per-set detail on the **activity** payload under `strength_data`. There is no separate endpoint or webhook type for it. If you receive activity data, you receive `strength_data`.

`strength_data` sits alongside `heart_rate_data` and the other activity fields. It is `null` on any activity with no strength content.

## Before you begin

* Receive activity data. If you are new to Terra, start with the [Quickstart](/unified-api/quickstart).

## Availability

Nothing to switch on. Strength data is part of the Unified API and available on every account. If you receive activity data from a source that reports sets, `strength_data` is already populated.

Terra does not replay webhooks it has already delivered. To get `strength_data` for an earlier workout, [re-request the activity](/unified-api/requesting-historical-data) over the REST API, which returns the same payload with `strength_data` filled in.

## Supported sources

Two kinds of source report sets: wearables that detect them, and training apps the user logs into.

| Source        | What the user connects with                                 | Notes                                                                                                                                                                                                                                                                                                                                                                             |
| ------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Garmin        | The usual Garmin connection                                 | Detected on the watch, so `source` is `device_detected`. See [Interpret the data](#interpret-the-data). Sets can be a moment behind the rest of the activity, so expect a later update filling in strength carrying the same `summary_id`.                                                                                                                                        |
| Coros         | The usual Coros connection                                  | Detected on the watch, so `source` is `device_detected`.                                                                                                                                                                                                                                                                                                                          |
| TrainingPeaks | The usual TrainingPeaks connection                          | Structured strength sessions, including coach-prescribed ones. Only sets the athlete actually performed are reported: a prescription they skipped is not. Coaches can also write their own exercises: those keep `exercise_name`, `reps` and `weight_kg`, but `movements`, the muscle lists and every `modifiers` axis are `null`, because nothing in the source classifies them. |
| Hevy          | Hevy API key                                                | Logged workouts, identified from Hevy's own catalogue. Also carries body metrics.                                                                                                                                                                                                                                                                                                 |
| wger          | wger username and password                                  | Logged workouts, identified from wger's own catalogue. Also carries body and nutrition.                                                                                                                                                                                                                                                                                           |
| Fitbod        | Fitbod username and password                                | Strength only.                                                                                                                                                                                                                                                                                                                                                                    |
| Strong        | Strong username and password                                | Strength only.                                                                                                                                                                                                                                                                                                                                                                    |
| StrongLifts   | Email address, then a one-time code StrongLifts emails them | Strength only.                                                                                                                                                                                                                                                                                                                                                                    |
| Lyfta         | Lyfta API key                                               | Strength only.                                                                                                                                                                                                                                                                                                                                                                    |
| Liftosaur     | Liftosaur API key                                           | Strength only. The key is a premium-account feature, so free Liftosaur accounts cannot be connected.                                                                                                                                                                                                                                                                              |

Every source reports through the same `strength_data` shape.

## Read the payload

`strength_data` sits on each entry of the activity payload's `data` array:

```json
{
  "type": "activity",
  "data": [
    {
      "metadata": { "summary_id": "…", "start_time": "…" },
      "strength_data": {
        "body_weight_kg": 78.5,
        "exercises": [
          {
            "exercise_name": "Paused Back Squat",
            "movements": ["squat"],
            "modifiers": { "implement": "barbell", "tempo": "paused" },
            "primary_muscles": ["quadriceps"],
            "secondary_muscles": ["glutes", "hamstrings", "abs"],
            "sets": [
              { "set_type": "warmup", "reps": 10, "weight_kg": 60,  "load_type": "external" },
              { "set_type": "normal", "reps": 4,  "weight_kg": 136, "load_type": "external", "rpe": 8.5 }
            ]
          }
        ]
      }
    }
  ]
}
```

{% hint style="info" %}
Fields are trimmed above for readability. **Terra always emits every documented key**: anything the source didn't report arrives as `null`, not missing. So test `strength_data` for non-null rather than checking whether the key exists, and expect `null` on fields the example omits.
{% endhint %}

**Don't gate on activity type.** Check `strength_data` for non-null instead, because strength work can arrive on more than one workout type.

### Request it over the REST API

The same payload comes back from the activity endpoint, so a backfill and a webhook give you identical objects:

```bash
curl --request GET \
  --url 'https://api.tryterra.co/v2/activity?user_id=<user_id>&start_date=2026-08-01&end_date=2026-08-08' \
  --header 'dev-id: <your-dev-id>' \
  --header 'x-api-key: <your-api-key>'
```

`end_date` is exclusive. See [Requesting historical data](/unified-api/requesting-historical-data) for the full endpoint.

## Read load correctly

`weight_kg` is meaningless on its own. Always read it with `load_type`:

```python
def set_volume_kg(s):
    # Only external load counts. Test FOR external: an unrecognised
    # load type must be treated as unknown, not counted.
    if s["load_type"] != "external":
        return 0
    return (s["weight_kg"] or 0) * (s["reps"] or 0)
```

A pull-up logged at `20 kg` with `load_type: "assisted"` means 20 kg was *removed* to help the lifter. Summing weight across every set counts that as 20 kg added, and does the same for bodyweight sets.

`bodyweight_plus` is excluded above on purpose: its `weight_kg` is the extra load only (the belt on a weighted pull-up), so total load needs `strength_data.body_weight_kg` added in. Include it if you want total load rather than added load.

Two more things `weight_kg` will not tell you:

* It is the load **as the source logged it**: a barbell's total, but a single dumbbell for dumbbell work. Sources do not agree on whether to double it, and Terra does not normalise it, because guessing wrong corrupts a lifter's history in either direction.
* `reps` is **per side** for unilateral movements, so check `modifiers.laterality` before doubling anything.

## Exercises and sets

An exercise is one or more `movements` plus a set of `modifiers`, not a single name from a fixed list, so **matching on `movements` gives you every variant of a lift**, including ones added after you wrote the query. A paused squat is `movements: ["squat"]` with `modifiers.tempo: "paused"`.

`movements` is a list because one exercise can chain several: a clean and jerk is `["clean", "jerk"]` and belongs in both clean volume and jerk volume. **Test membership, never equality:**

```python
def squat_volume_kg(strength_data):
    total = 0
    for exercise in strength_data["exercises"] or []:
        if "squat" not in (exercise["movements"] or []):
            continue          # catches front, box, paused, Zercher, sumo, …
        for s in exercise["sets"]:
            total += set_volume_kg(s)
    return total
```

Read `modifiers` only when the variant matters, for example `modifiers.implement == "barbell"` to exclude goblet squats. An axis that is `null` means the source **didn't report it**, not that the default applies: a squat with no `implement` is not a bodyweight squat.

Sets are nested inside their exercise in the order performed. Exercises performed together in a superset or circuit share a `group_id`.

An exercise can arrive with an empty `sets` array: the user added it to the workout and logged nothing against it. Filter those out if you only want performed work.

### Unresolved exercises

`movements` can be `null`. It happens most often with exercises the user or their coach wrote themselves, which the source stores as free text and never classifies:

```json
{ "exercise_name": "Leg Press mit beiden Beinen", "movements": null,
  "modifiers": null,
  "sets": [ { "reps": 12, "weight_kg": 120, "load_type": "external" } ] }
```

The sets are still complete, so volume and load work as normal. Only the rollup is missing. `exercise_name` always carries the source's own label, so display keeps working.

Don't parse `exercise_name`. Its shape follows the source: a training app sends what the user sees (`Close Grip Bench Press`), a watch sends its own catalogue key (`triceps_pressdown`). Use it for display, and `movements` and `modifiers` for logic.

## Interpret the data

### Logged and detected values

The same field means different things depending on how the exercise was captured, and it's worth surfacing that difference to your users rather than presenting both identically:

* `user_logged`: the user recorded it in a training app. Reps and load are exactly what they entered.
* `device_detected`: a wearable inferred it from motion. Reps and the exercise itself are estimates, and `weight_kg` is `null` more often: the device doesn't measure load, so it's present only when the user added it afterwards.

A watch also won't always resolve a set into an exercise. Where it recorded that work happened but couldn't classify it, the sets are reported with `movements` unresolved rather than guessed. See [Unresolved exercises](#unresolved-exercises).

### Muscles

`primary_muscles` is the focus of the exercise, `secondary_muscles` the work it also involves. Every source uses the same vocabulary, so a per-muscle rollup works across all of them, but how specific they are varies, so treat them as a grouping rather than a precise per-exercise judgement.

A whole-body lift, such as an olympic lift, a loaded carry or a burpee, reports **every muscle it works as primary**, with no secondaries, because no single muscle is the focus.

### Unknown and null values

`set_type`, `load_type`, `source` and the muscle lists report `unknown` when the source said something that couldn't be resolved. `null` means it said nothing at all. The distinction matters when you're deciding whether to show a gap or a question mark, and for `load_type`, whether to count the set at all.

### Unrecognised values

Movements, targets, muscles and the modifier axes are **open vocabularies**: the set of values can grow. Treat a value you don't recognise as unknown rather than switching exhaustively over the ones you know. An unrecognised value is not a breaking change, and code that rejects one will break when it appears.

Muscles carry one extra caveat: an unrecognised member can shift a per-muscle total even though it never breaks parsing. If you aggregate per muscle, see the [data models reference](https://docs.tryterra.co/reference/health-and-fitness-api/data-models) for which members group together.

Full field lists, types and the complete vocabularies: [Data models](https://docs.tryterra.co/reference/health-and-fitness-api/data-models).

## Next steps

* [Health data events](/unified-api/receiving-data-updates): handle activity payloads as they arrive.
* [Historical data requests](/unified-api/requesting-historical-data): re-request earlier workouts to get their `strength_data`.
* [Activity types](https://docs.tryterra.co/reference/health-and-fitness-api/data-models#activitytype): map `metadata.type` to an activity name.


# Troubleshooting

Find out why data events are not arriving for a user, and check the account, the provider sync and the mobile SDK setup.

When an end user reports missing data, work through the common causes on this page: the wrong account, data that has not synced to the provider's cloud, and known mobile SDK issues.

## Common reasons for missing data

Terra sends data automatically as soon as it is available on a data source's cloud. Here are a few potential reasons why you're not receiving Data Events:

1. If the user has connected to the wrong account.
2. If the wearable hasn't synced to the respective app on the end user's phone, or if the app has not synced to the cloud, Terra will be unable to retrieve that data.
3. If you have not completed additional destination configurations (e.g. to [integrations requiring dedicated credentials](/unified-api/dedicated-data-source-api-keys)).
4. If your Destination is incorrectly configured. If this is the case, you can see 400 or 500 errors in the [Event log](https://dashboard.tryterra.co/dashboard/events) in your Terra dashboard.

## First things to try

* Wait a bit longer to rule out regular data delays from the data sources.
* Try to force a sync (using a "pull down to sync" feature or equivalent available in most apps).
* To verify the data has synced to the respective cloud, have the user open the web dashboard for their device in a browser and check the data is present.
* Submit a support ticket via your Terra dashboard if you are unsure.

{% prompt description="Triage a user with no data arriving" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
No data is arriving for user 8f2a1c. Check whether the connection is active, whether any deliveries failed, and what the last event Terra sent was.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## Check the user connected the right account

Some users log in with the wrong account, and this happens more often than you'd think. In order to verify the account that they're using matches with the Terra user ID that they've generated, you may follow the following procedure for the integrations below.

### Get the provider's user ID

Terra always provides a `user_id` for each connection. To get the user ID that the provider (e.g. Garmin, Fitbit etc) uses, you can use the [https://docs.tryterra.co/reference/health-and-fitness-api/athlete](https://docs.tryterra.co/reference/health-and-fitness-api/athlete "mention") endpoint in order to retrieve that, which will be under the field `provider_user_id`. Once you have obtained that, follow the guidelines below for each provider.

### Fitbit

Launch your Fitbit app (make sure you're using the latest Fitbit app version), click your Fitbit avatar in the top left corner, then click your Fitbit display name to view your profile. Then Click "Personal" and go to the next page, your Fitbit User ID is located at the bottom.

![](https://files.readme.io/369b62f-image.png)

Check to make sure your user's Fitbit user ID matches the one retrieved by the [https://docs.tryterra.co/reference/health-and-fitness-api/athlete](https://docs.tryterra.co/reference/health-and-fitness-api/athlete "mention") endpoint

### MyFitnessPal

Using the `provider_user_id` obtained above, navigate to [https://www.myfitnesspal.com/food/diary/{provider\_user\_id}](https://www.myfitnesspal.com/food/diary/%7Bprovider_user_id%7D) .

**Invalid username.** Seeing a page like this:

![](https://files.readme.io/b2e0cc6-image.png)

indicates that the username entered by the end user is invalid. In the case above, the user accidentally entered **their email** instead of **their username**. Have them log in once more, following the "how-to" guide presented in the login screen

**Disabled diary sharing.** The page below:

![](https://files.readme.io/9e78b18-image.png)

Indicates the user failed to enable diary sharing/disabled it since they authenticated through Terra. In order to remediate this, have the user re-enable diary sharing with the same password used during initial authentication, or have them re-authenticate after having enabled diary sharing as per the "how-to" guide in the login screen

## Check the data synced from the device

In those cases the first step is always to ensure that the data is showing up in the partner app (e.g. Garmin Connect, Fitbit, etc..).

Next would be to check if the data is correctly synchronized with the partner cloud, by using their web portal.

### Garmin

Ensure that the data is showing up in [the Garmin connect web dashboard](https://connect.garmin.com/modern/). If not, then pull down from the top in the Garmin connect mobile app, and hit the circle arrow until everything refreshes. If the data shows up in the web dashboard for Garmin Connect, but not through the API after 1-2 minutes, please contact support.

![](https://files.readme.io/3efde45-ezgif.com-optimize.gif)

### Apple Health

The most likely cause is background updates not running. To check, request a backfill for the user in your Terra dashboard: open [Users](https://dashboard.tryterra.co/dashboard/users), select the user, and choose **Backfill** under **Get data**. The device uploads the window the next time the SDK runs.

If data does come through, this means that background delivery is not operating as expected. To Troubleshoot, follow the steps below.

**Battery saving mode is on.** Have the user go to Settings > Battery, and make sure "Low Power Mode" is turned **OFF**

**Background app refresh is turned off for your app.** Have the user visit Settings > General > Background App Refresh, and verify that your app is toggled on.

![](https://files.readme.io/27bfad6-RPReplay_Final1719410146-ezgif.com-optimize.gif)

### Google Fit

Go inside the Google Fit app, and ensure that your data is up to date on the display. Thereafter, pull down from the top of the screen to synchronize with the cloud. Please note that even after that, there can be some delay for Google to make the data available through their API. You should be able to see that data after at most 30-60 minutes in most cases.

![](https://files.readme.io/28c7b76-RPReplay_Final1719407216-ezgif.com-optimize.gif)

**On iOS**, ensure background app refresh is turned on for Google Fit

![](https://files.readme.io/27bfad6-RPReplay_Final1719410146-ezgif.com-optimize.gif)

## Mobile SDK known issues

### Health Connect

{% hint style="warning" %}
This section applies when you read Samsung Health or other apps' data **through** Health Connect: `Source.HEALTH` in the [Android SDK](/mobile-sdks/android-sdk-2), or `'health'` on Android in the [React Native SDK](/mobile-sdks/react-native-sdk-2). If you read Samsung Health directly (`Source.SAMSUNG_HEALTH` or `'samsungHealth'`), see the next section.
{% endhint %}

Health Connect is Google's on-device health store. The SDK can only read what other apps have written into it.

{% hint style="danger" %}
**Health Connect known issues**

Apps sometimes fail to write into Health Connect because of bugs in Health Connect itself. For example, Samsung Health may not send **steps** into Health Connect. In other cases Health Connect data cannot be read at all, so little or no data syncs.

Before release, submit the Health Connect declaration in the Google Play Console, listing the data types your app reads. See [Apply for Health Connect access](/mobile-sdks/android-sdk-2#configure-health-permissions).
{% endhint %}

### Samsung Health direct access

This section applies when you read Samsung Health directly with the `terra-android-samsung` add-on: `Source.SAMSUNG_HEALTH` in the Android SDK, or `'samsungHealth'` in the React Native SDK. See [Samsung Health](/mobile-sdks/samsung-health) for setup.

{% hint style="info" %}
**Samsung Health permission sheet not appearing**

If the permission sheet does not appear, `permissions.request` throws `TerraError.HealthDataUnavailable` with the reason (in React Native, it rejects with `health_data_unavailable`). Call `terra.availability(Source.SAMSUNG_HEALTH)`, or `terra.availability('samsungHealth')` in React Native, to read the reason without a connection. React Native returns each reason as a `kind` in camelCase, such as `providerAppMissing`. The reasons are:

* `ModuleMissing`: the `terra-android-samsung` add-on is not in the app. In React Native, set `terraSamsungHealth=true` in `android/gradle.properties`.
* `ProviderAppMissing`: Samsung Health is not installed, is disabled, or is not set up on the device.
* `ProviderAppTooOld`: Samsung Health needs an update.
* `PartnerPolicyMissing`: Samsung has not approved your app for these data types. Until it does, turn on Samsung Health's developer mode on test devices: in Samsung Health, open **Settings > About Samsung Health** and tap the version number repeatedly.
  {% endhint %}

{% hint style="warning" %}
**App crashes in release builds with the 1.x SDK**

This applies to the 1.x SDKs only (`terra-android` 1.x, `terra-react` and `terra-flutter`). If your app works in debug but crashes when it uses Samsung Health in a release build, R8 has stripped Samsung SDK classes and you get `ClassNotFoundException` at runtime. Add this rule to `proguard-rules.pro`:

```proguard
-keep class com.samsung.android.** { *; }
```

With 2.x, Samsung's Health Data SDK 1.1.0 carries its own keep rules, so no rule is needed.
{% endhint %}

## Next steps

* [Event delivery](/destinations/events): see how Terra delivers events and retries failed attempts.
* [Historical data requests](/unified-api/requesting-historical-data): backfill the gap once the cause is fixed.
* [Mobile SDKs](/mobile-sdks/mobile-only-sources): set up Apple Health, Samsung Health and Health Connect.


# Pricing

Learn how Unified API credits are charged on the Quick Start plan, and how add-on products are priced.

Terra pricing starts with the Unified API on the Quick Start plan, which uses usage-based pricing in Unified API credits. Add-on products extend the plan, and each is priced on its own. This page explains how both work.

## At a glance

* 100,000 included Unified API credits that reset monthly.
* Tiered pricing and volume discounts as your user base grows.
* Usage Spike Protection if your usage spikes unexpectedly in your first 6 months.
* The included credits cover 500 active authentications a month, each with up to 400 events.
* Add products as you need them.

## Unified API

### How credits work

1. **Monthly allowance:** Your Quick Start subscription gives you 100,000 free Unified API credits each month.
2. **Usage:** Unified API usage consumes Unified API credits, based on connected users and events.
3. **Monthly reset:** Unified API credits reset to 100,000 each billing period and do not roll over.
4. **Scaling:** Only pay for Unified API credits beyond your 100,000 monthly allowance. Additional usage is billed monthly.
5. **Volume discount:** The more Unified API credits you use, the cheaper each one gets (tiered pricing).

### Credit prices

Your Quick Start subscription includes 100,000 monthly Unified API credits, covering the needs of most startups during their initial launch and growth phases. Tiered pricing applies beyond this:

| Total monthly Unified API credits consumed | Cost per additional credit    |
| ------------------------------------------ | ----------------------------- |
| 0 - 100,000                                | $0 (Included in subscription) |
| 100,001 - 1,000,000                        | $0.005                        |
| 1,000,001+                                 | $0.003                        |

### Usage Spike Protection

Rapid growth or a testing error can cause an unexpected bill. Usage Spike Protection covers this.

* If you receive an unexpectedly large bill in your initial 6 months (counted from the first invoice charged to your card) due to a significant spike from rapid user growth or a testing or implementation error, you may be eligible for a one-time refund. Specific criteria apply, such as bill threshold or usage increase.
* Contact the support team. We'll review your situation, work towards refunding the unexpected amount, and help you optimise future usage.

### What consumes credits

The number of Unified API credits consumed monthly scales with your number of users (active authentications) and events.

<table><thead><tr><th>About</th><th valign="top">Active authentications</th><th>Events</th></tr></thead><tbody><tr><td><strong>What it is</strong></td><td valign="top">An active authentication represents an end-user's wearable, sensor, or fitness app that has been authenticated with Terra</td><td><p>Data payloads and notifications sent by Terra to your backend. This includes:</p><ul><li><em>Data Sync Events:</em> Health, activity, sleep, workout data, etc.</li><li><em>Authentication Events:</em> User authentication status or permission updates.</li></ul></td></tr><tr><td><strong>How it's measured</strong></td><td valign="top"><p>An active authentication represents a health data source that both:</p><ol><li>Has been authenticated by an end user</li><li>Has not been deauthenticated</li></ol></td><td><p>Each individual event transmission is counted.</p><ul><li>Example: A webhook sending a Daily payload for one end-user is one event</li><li><p>Free tier: 400 events per active authentication</p><ul><li><em>95% of customers are never charged for events</em></li></ul></li></ul></td></tr><tr><td><strong>Cost</strong></td><td valign="top">200 Unified API credits per active authentication per month</td><td><p>The first 400 events per active authentication are free.</p><p>0.5 Unified API credits per event beyond this.</p></td></tr></tbody></table>

### Model credits

<table><thead><tr><th>About</th><th valign="top">Model run</th></tr></thead><tbody><tr><td><strong>What it is</strong></td><td valign="top">A model run applies one of Terra's health models (e.g. Sleep Window, Health Terrain) to a single user's data for a date range, returning a ready-to-use insight.</td></tr><tr><td><strong>How it's measured</strong></td><td valign="top">Each run counts as one, regardless of how much data the date range covers. Running two models, or the same model on two users, is two runs.</td></tr><tr><td><strong>Cost</strong></td><td valign="top">1 credit per model run ($0.01 per credit).</td></tr></tbody></table>

## Add-on products

Add-on products extend your plan. Activate them from **Settings → Plans & Pricing → Additional Products** on the dashboard. Each add-on is billed separately from your plan fee.

Add-ons that use credits have their own credit balance. Add-on usage never draws down your Unified API credits, and Unified API usage never draws down an add-on's credits. Each add-on's pricing page explains what consumes its credits.

| **Add-on**                                                    | **Price**              | **Includes**                            |
| ------------------------------------------------------------- | ---------------------- | --------------------------------------- |
| [Lab Reports API](/lab-reports/pricing)                       | $499/month + usage     | 100,000 Lab Reports credits a month     |
| [Planned Workouts](/planned-workouts-api/pricing)             | $99/month + usage      | 20,000 Planned Workouts credits a month |
| [Streaming API](/streaming-api/pricing)                       | $99/month + usage      | 20,000 Streaming credits a month        |
| [Health Scores](/user-engagement/health-scores-pricing)       | $499/month             | 14-day free trial                       |
| [Graph API](/graphs/pricing)                                  | $50/month per 2 graphs | -                                       |
| [Health Rewards](https://tryterra.co/products/health-rewards) | Contact us             | -                                       |


# WHOOP

WHOOP requires every company to connect users through its own app on the [WHOOP developer portal](https://external-developer-portal.whoop.com/), with its redirect and webhook URLs on a domain that belongs to you. Your Terra dashboard sets up that domain and shows the exact URLs to use.

## Create the app

1. Create a WHOOP account with the WHOOP mobile app, then log in to the [WHOOP developer portal](https://external-developer-portal.whoop.com/).
2. Create a team with your company details.
3. Create an app. Leave the redirect and webhook URL fields until the dashboard gives you the values in the next section.

## Set it up in the dashboard

In your Terra dashboard, open **Connections**, choose **WHOOP** and follow the setup. It walks you through your custom domain and then shows the Redirect URL and Webhook URL to paste into your app.

In the WHOOP developer portal:

* Set the webhook model to **v2**.
* Tick every scope:

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FSGZHhvNaUamUDwEMKMj1%2Fimage.png?alt=media&amp;token=a00c52ff-ab96-4a43-9c94-49b66717a87d" alt="WHOOP app settings with every scope ticked"><figcaption></figcaption></figure>

* Apply for production access. If WHOOP contacts you for more information during the review, let us know and we can help.

Then enter the app's client ID and client secret in the dashboard and save.


# Dexcom

Dexcom requires every company to connect users through its own app on the [Dexcom developer portal](https://developer.dexcom.com/account/apps), with its redirect URL on a domain that belongs to you. Your Terra dashboard sets up that domain and shows the exact URL to use.

## Create the app

1. Create a Dexcom developer account and log in to the [Dexcom developer portal](https://developer.dexcom.com/account/apps).
2. Create an app with your company details. Leave the redirect URL until the dashboard gives you the value in the next section.

## Set it up in the dashboard

In your Terra dashboard, open **Connections**, choose **Dexcom** (or **Dexcom EU**) and follow the setup. It walks you through your custom domain and then shows the Redirect URL to paste into your app.

When you are ready, apply for a production upgrade. If Dexcom contacts you for more information, let us know and we can help.

{% hint style="info" %}

#### Discussing a production upgrade with Dexcom

When discussing the production upgrade with Dexcom, the relationship being set forward is entirely between your company and Dexcom, and Terra should not be mentioned in the process, as a third party building with the integration for you.
{% endhint %}

Then enter the app's client ID and client secret in the dashboard and save.


# Overview

Choose where Terra sends events from the Unified API and other products, add the destination in the dashboard, and allow Terra's IP addresses.

A destination is where Terra sends events: a webhook, a database, cloud storage or a queue. Destinations belong to an [environment](/unified-api/understanding-terra-environments), and every product in that environment delivers to them:

* **Unified API:** auth events and health data from your users' wearables and apps.
* **Lab Reports:** results from the lab reports you upload.
* **Planned Workouts API and Routes API:** planned workouts and routes received from or revised on a user's provider.

A destination receives every event type unless you limit it to chosen types with its `event_types` setting in the [Admin API](https://docs.tryterra.co/reference/admin-api/overview). This page lists the destination types and how to add one. [Event delivery](/destinations/events) explains what Terra sends and how delivery and retries work.

{% hint style="info" %}
**Vantage API doesn't use destinations.** It sends order and result updates to a single webhook URL that you set for Vantage. See [Configure your webhook endpoint](/vantage-api/account-setup-and-api-keys#configure-your-webhook-endpoint) and [Vantage webhooks](/vantage-api/webhooks).
{% endhint %}

## Choose a destination

* [Webhooks](/destinations/webhooks): Terra makes a POST request to your URL with each new event.
* [SQL database (Postgres, MySQL)](/destinations/sql-database-postgres-mysql): Terra creates the tables and inserts a row per event, with download links for the full payloads.
* [Supabase](/destinations/supabase): Postgres tables and S3-compatible storage in one platform, provisioned automatically through OAuth.
* [Cloud storage (S3, GCS, Azure Blob)](/destinations/cloud-storage-s3-gcp): raw payloads written to your bucket, for archival, batch processing or a data lake.
* [Queues (SQS, Kafka)](/destinations/queuing-services-sqs-kafka): messages published to your managed queue for asynchronous ingestion.
* [MongoDB](/destinations/mongodb): full payloads stored in your MongoDB collections, with indices created for you.
* [Firestore](/destinations/firestore): full payloads stored as documents in your Google Cloud Firestore database.

## Add a destination

1. Open the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard.
2. Click **Add New** and choose a destination type: Webhook, Database, Bucket and other.
3. Add the necessary details and click **Apply**.

Each destination page lists the details it needs.

{% prompt description="Add a webhook destination and get its signing secret" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Add a webhook destination to my testing environment pointing at https://example.com/terra, and give me the signing secret so I can verify payloads.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

{% hint style="info" %}
**Don't have a destination yet?** If you are just starting off building your product and want to test how Terra works, you can use [https://webhook.site](https://webhook.site/#!/) to set up a temporary destination for webhooks.
{% endhint %}

## IP allowlist

Terra sends data to your destinations from a fixed set of IP addresses. If your infrastructure uses a firewall or IP access list, add the following IPs to ensure Terra can reach your destination:

* `18.133.218.210`
* `18.169.82.189`
* `18.132.162.19`
* `18.130.218.186`
* `13.43.183.154`
* `3.11.208.36`
* `35.214.201.105`
* `35.214.230.71`
* `35.214.252.53`

{% hint style="warning" %}
These IPs apply to all data destinations: webhooks, databases, queues, and storage buckets. Allow them wherever you accept connections from Terra.
{% endhint %}

## Next steps

* [Webhooks](/destinations/webhooks): set up the most common destination.
* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what Terra sends and how delivery works.


# Event delivery

Learn what events, deliveries and attempts are, what their statuses mean, and how retries and resends work.

When something changes for one of your users, Terra creates an **event** and sends it to your destinations. Three objects describe that journey:

* An **event** is the thing that happened, such as new sleep data or a user connecting a provider.
* A **delivery** is that event on its way to one destination. An event has one delivery per destination.
* An **attempt** is one request Terra sends for a delivery. A delivery has one attempt per send, retry and resend.

## An example

A user's sleep syncs. Your environment has two destinations: a webhook and an S3 bucket. Your webhook server was down for a few minutes.

```mermaid
flowchart TB
    E["<b>Event</b><br/>evt_123<br/>unified_api.sleep.updated"]
    D1["<b>Delivery</b><br/>webhook<br/>api.example.com/terra"]
    D2["<b>Delivery</b><br/>s3<br/>my-bucket"]
    A1["<b>Attempt 1</b><br/>10:00:02 · 503"]
    A2["<b>Attempt 2</b><br/>10:01:05 · 503"]
    A3["<b>Attempt 3</b><br/>10:05:40 · 200"]
    A4["<b>Attempt 1</b><br/>10:00:03 · 200"]

    E --> D1
    E --> D2
    D1 --> A1
    D1 --> A2
    D1 --> A3
    D2 --> A4

    classDef failed stroke:#F04438,stroke-width:2px
    classDef ok stroke:#12B76A,stroke-width:2px
    class A1,A2 failed
    class A3,A4 ok
```

* There is **one event**, because one thing happened.
* There are **two deliveries**, because there are two destinations.
* The webhook delivery took **three attempts**: two failed while the server was down, and a retry succeeded.
* The bucket delivery took **one attempt**. The webhook's failures did not delay it.

Each delivery succeeds or fails on its own. One broken destination never holds back the others.

## Event IDs and types

Every event has an `event_id`. Your webhook receives it in the `terra-reference` header. Every delivery, retry and resend of an event carries the same `event_id`, so use it to recognise an event you have already processed.

An event's `type` says what happened, in the form `<product>.<resource>.<action>`, for example `unified_api.sleep.updated` or `unified_api.auth.succeeded`. See [Event types](https://docs.tryterra.co/reference/health-and-fitness-api/event-types) for the payload each one carries.

## Delivery status

Start with the delivery. Its status says where the event stands for one destination.

| Status      | Meaning                                                                                                              |
| ----------- | -------------------------------------------------------------------------------------------------------------------- |
| `pending`   | Not delivered yet. Terra tries again at `next_attempt_at`.                                                           |
| `delivered` | The destination accepted the event. For a webhook, that means a 2xx response.                                        |
| `failed`    | Terra sent at least one request, then stopped trying. Usually the retries ran out.                                   |
| `canceled`  | Terra decided not to send before sending any request, for example because the destination was deleted or turned off. |

To see why a delivery failed or was canceled, look at its last status code. When there is no HTTP status to show, `no_status_reason` explains instead, for example `timed_out` or `destination_deleted`.

## Event status

An event's status sums up its deliveries, so you can scan a list of events without opening each one.

| Status      | Meaning                                                                                     |
| ----------- | ------------------------------------------------------------------------------------------- |
| `pending`   | At least one delivery is still `pending`.                                                   |
| `failed`    | No delivery is pending, and at least one `failed`.                                          |
| `canceled`  | Every delivery was `canceled`. No destination was sent the event.                           |
| `delivered` | Every other case: each destination got the event, or was canceled after another one got it. |

A `failed` event may still have reached some of your destinations. Open it to see which delivery failed.

## Retries

When an attempt fails, the delivery stays `pending` and Terra tries again later, with exponential backoff, for several hours. An attempt fails when the destination returns anything other than a 2xx, does not answer within 8 seconds, or cannot be reached. Retries always go to the destination's current URL.

When the retries run out, the delivery becomes `failed` and Terra stops trying. Terra does not notify you when this happens, so monitor your endpoint, or check the Events page for failed events.

The number and timing of retries can change, so don't depend on a specific schedule. For timeouts and the circuit breaker that pauses a failing webhook, see [Webhooks](/destinations/webhooks#timeout-and-circuit-breaker).

## Resends

A resend sends an event to one destination again. It adds new attempts to that destination's existing delivery, each marked with the resend's `resend_id`. It does not create a new event or a new delivery. A resend runs alongside any automatic retries rather than replacing them.

Resend failed events once your destination is fixed. Your server can receive the same event more than once, so deduplicate on `event_id`.

## View and resend events

* **Dashboard:** the [Events](https://dashboard.tryterra.co/dashboard/debug) page lists events for 30 days. Open one to see each delivery, every attempt, and when the next retry is due. You can view an event's payload for about 14 days, and resend it from there.
* **Terra CLI:** `terra events list --status failed` finds failed events, `terra events retrieve <EVENT_ID>` shows their deliveries and attempts, and `terra events resend` sends one again. See the [command reference](https://docs.tryterra.co/developer-tools/terra-cli/command-reference).

{% prompt description="Find failed events and resend them" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Show me every failed event in production from the last 24 hours, tell me which destination each one failed on and why, and resend the ones for user 9ebfb96d-e376-4c17-8d4b-0e85db39b1b5.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## Next steps

* [Health data events](/unified-api/receiving-data-updates): handle the data events Terra sends for connected users.
* [Historical data requests](/unified-api/requesting-historical-data): backfill data from before a user connected.
* [Webhooks](/destinations/webhooks): verify signatures, and see how timeouts and the circuit breaker work.


# Webhooks

Receive Terra events as POST requests to your URL, verify their signatures, and handle retries, timeouts and ping mode.

Webhooks are the most basic [destination](/destinations/setting-up-data-destinations) to set up, and involve Terra making a POST request to a predefined callback URL you pass in when setting up the Webhook.

They are automated messages sent from apps when something happens.

Terra uses webhooks to notify you whenever new data is made available for any of your users. New data, such as activity, sleep, etc will be normalised and sent to your webhook endpoint URL where you can process it however you see fit.

After a user authenticates with your service through Terra, you will automatically begin receiving webhook messages containing data from their wearable.

## Before you begin

* A URL on your server that accepts POST requests. For testing, you can use [webhook.site](https://webhook.site/#!/) as a temporary endpoint.

## Add the destination in Terra

1. Open the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard.
2. Click **Add New** and select Webhook.
3. Enter your callback URL and click **Apply**.

## Secure your endpoint

Exposing a URL on your server can pose a number of security risks, allowing a potential attacker to

* **Launch denial of service (DoS) attacks** to overload your server.
* **Tamper with data** by sending malicious payloads.
* **Replay legitimate requests** to cause duplicated actions.

among other exploits.

In order to secure your URL, Terra offers two separate methods of securing your URL endpoint: payload signing and IP allowlisting.

### Verify the signature

Every webhook sent by Terra includes an HMAC-based signature header `X-Terra-Signature`, which takes the form:

```
t=1723808700,v1=a5ee9dba96b4f65aeff6c841aa50121b1f73ec7990d28d53b201523776d4eb00
```

In order to verify the payload, you may use one of Terra's SDKs as follows:

{% hint style="warning" %}
Terra requires the **raw, unaltered** body of the request to perform signature verification. If you’re using a framework, make sure it doesn’t manipulate the raw body (many frameworks do by default)

**Any** manipulation to the raw body of the request causes the verification to fail.
{% endhint %}

{% tabs %}
{% tab title="Python SDK" %}

```python
import os

from flask import Flask, jsonify, request
from terra.utils.verify_signature import verify_terra_webhook_signature

app = Flask(__name__)

signing_secret = os.getenv('SIGNING_SECRET')  # Your signing secret from Terra

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('x-terra-signature')
    body = request.get_data(as_text=True)

    if signature is None:
        return jsonify({"error": "x-terra-signature header missing"}), 400

    try:
        is_valid = verify_terra_webhook_signature(
            payload=body, signature_header=signature, signing_secret=signing_secret
        )
        if not is_valid:
            return jsonify({"error": "Invalid signature"}), 400

        # Process the webhook data here
        webhook_data = request.get_json()
        print(f"Received valid webhook data: {webhook_data}")

        return jsonify({"message": "Webhook received successfully"}), 200

    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(port=8000)
```

{% endtab %}

{% tab title="Javascript SDK" %}

```javascript
const express = require("express");
const { verifyTerraWebhookSignature } = require("terra-api");

const app = express();

// Use the built-in Express middleware to parse raw JSON bodies.
// This must be placed before the webhook endpoint.
app.use(
    express.raw({
        inflate: true,
        limit: "4000kb", // Set a limit appropriate for your use case
        type: "application/json",
    })
);

// Make the route handler function async
app.post("/consumeTerraWebhook", async (req, res) => {
    try {
        const signature = req.headers["x-terra-signature"];
        const secret = process.env.TERRA_SECRET;

        // First, verify the signature. The function will throw an error if verification fails.
        // The req.body is a Buffer, which is the expected format.
        await verifyTerraWebhookSignature(req.body, signature, secret);

        // If verification is successful, send a 200 OK response immediately.
        res.sendStatus(200);

        // Process the data *after* responding to prevent timeouts.
        const data = JSON.parse(req.body.toString("utf8"));
        console.log("Received & Verified Terra Webhook Data:");
        console.log(JSON.stringify(data, null, 2));

    } catch (error) {
        // If verifyTerraWebhookSignature throws an error, catch it here.
        console.error("Webhook verification failed:", error.message);
        return res.sendStatus(401); // Respond with Unauthorized
    }
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server started on http://localhost:${port}`);
});
```

{% endtab %}

{% tab title="Java SDK" %}

```java
import co.tryterra.terraclient.WebhookHandlerUtility;

// Using the Spark framework (http://sparkjava.com)
public Object handle(Request request, Response response) {
    String payload = request.body();
    String sigHeader = request.headers("x-terra-signature");

    // Find your secret on https://dashboard.tryterra.co/dashboard/connections
    WebhookHandlerUtility handlerUtility = new WebhookHandlerUtility("SIGNING_SECRET");

    boolean validSignature = handlerUtility.verifySignature(sigHeader, payload);

    if (!validSignature) {
        response.status(401);
        return "";
    }

    // Deserialize the object inside the event & handle the event
    // ...
    response.status(200);
    return "";
}
```

{% endtab %}

{% tab title="Manual verification" %}
We recommend that you use our official libraries to verify webhook event signatures. You can however create a custom solution by following this section.

The `X-Terra-Signature` header included in each signed event contains **a timestamp** and **one or more signatures** that you must verify.

* the timestamp is prefixed by `t=`
* each signature is prefixed by a ***scheme***. Schemes start with `v`, followed by an integer. (e.g. `v1`)

```
X-Terra-Signature:
t=1492774577,
v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd,
v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39
```

Terra generates signatures using a hash-based message authentication code ([HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)) with [SHA-256](https://en.wikipedia.org/wiki/SHA-2). To prevent [downgrade attacks](https://en.wikipedia.org/wiki/Downgrade_attack), ignore all schemes that aren’t `v1`

To create a manual solution for verifying signatures, you must complete the following steps:

**Step 1: Extract the timestamp and signatures from the header**

Split the header using the `,` character as the separator to get a list of elements. Then split each element using the `=` character as the separator to get a prefix and value pair.

The value for the prefix `t` corresponds to the timestamp, and `v1` corresponds to the signature (or signatures). You can discard all other elements.

**Step 2: Prepare the `signed_payload`string**

The `signed_payload` string is created by concatenating:

* The timestamp (as a string)
* The character `.`
* The actual JSON payload (that is, the request body)

**Step 3: Determine the expected signature**

Compute an HMAC with the SHA256 hash function. Use the endpoint’s signing secret as the key, and use the `signed_payload` string as the message.

**Step 4: Compare the signatures**

Compare the signature (or signatures) in the header to the expected signature. For an equality match, compute the difference between the current timestamp and the received timestamp, then decide if the difference is within your tolerance.

To protect against timing attacks, use a constant-time-string comparison to compare the expected signature to each of the received signatures.
{% endtab %}
{% endtabs %}

### Signing secret

Each webhook has its own signing secret. Verify a webhook's deliveries with that webhook's secret. A new webhook gets its own secret when you create it. Webhooks created earlier may still share your environment's secret until you rotate them.

To find it, open the [Connections page](https://dashboard.tryterra.co/dashboard/connections), click the key icon on the webhook, and copy **Signing secret**. It always shows the secret that webhook's deliveries are currently signed with.

### Rotate a signing secret

Rotating gives one webhook a new secret. Deliveries to that webhook are signed with the new secret straight away. Your other webhooks keep theirs. Verification itself does not change: same header, same HMAC-SHA256 scheme, only the key is new.

{% stepper %}
{% step %}
**Make sure your endpoint returns a non-2xx status when a signature does not match**, for example `401`. Terra then retries the delivery instead of treating it as delivered.
{% endstep %}

{% step %}
**Rotate the secret.** On the Connections page, click the key icon on the webhook, then **Rotate secret** and confirm. Only account admins can rotate. The new secret is shown unmasked: copy it.
{% endstep %}

{% step %}
**Update your endpoint to verify with the new secret** and deploy.
{% endstep %}
{% endstepper %}

Deliveries that arrive between the rotation and your deploy fail verification and get your non-2xx response. Terra retries them for several hours (see [Retries](#retries)), and each retry is signed with the current secret, so they verify once your endpoint has the new one.

You can also rotate with the [admin API](https://docs.tryterra.co/reference/admin-api/webhook-signing-secrets) or the Terra CLI.

### Allow Terra's IPs

An IP allowlist lets you to only allow requests from a preset list of allowed IPs. An attacker trying to reach your URL from an IP outside this list will have their request rejected.

Terra sends all outbound requests (webhooks, database connections, etc.) from the same set of IPs. See the [full IP list on the Destinations page](/destinations/setting-up-data-destinations#ip-allowlist).

## Retries

A webhook attempt fails when your server responds with anything other than a 2xx, including a 3xx redirect, or does not respond within 8 seconds. Terra then retries the delivery with exponential backoff for several hours. When the retries run out, the delivery becomes `failed` and Terra does not notify you.

Resend failed events from the [Events](https://dashboard.tryterra.co/dashboard/debug) page of the dashboard once your endpoint is fixed. [Event delivery](/destinations/events#retries) has the full retry and resend rules.

{% prompt description="Find failed webhook deliveries and resend them" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Show me every failed webhook delivery in production from the last 24 hours, and resend the ones for user 9ebfb96d-e376-4c17-8d4b-0e85db39b1b5.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

## Timeout and circuit breaker

Terra waits **8 seconds** for your server to respond before considering the request timed out.

When a destination shows a sustained high failure rate, Terra activates a **per-destination circuit breaker** that briefly pauses delivery. This protects your server from continued load while it's clearly unhealthy and protects Terra's delivery pipeline from spending capacity on requests that are unlikely to succeed.

**What trips the circuit:**

* Client-side **timeouts** (your server didn't respond within 8 seconds).
* HTTP **5xx** responses from your server.
* HTTP **4xx** responses that persist across several delivery attempts on the same event. A 4xx on an event's early attempts is treated as a per-message issue. Only sustained 4xx across retries is taken as evidence that the destination itself is misconfigured.

The breaker only fires on **unambiguous meltdowns**: a destination that is failing the vast majority of recent attempts over a meaningful sample. A handful of failures or a mild degradation (e.g. occasional timeouts) does not trip the circuit; the rest of your traffic flows normally.

**While the circuit is open:**

* Data events for that destination are held back, not attempted, and re-queued with the same exponential backoff used for normal retries.
* Each re-queue counts toward the delivery's retry limit, even though no request was sent. If the destination stays broken until the retries run out, the delivery fails without ever reaching your server.
* **Authentication and de-authentication events still flow during a circuit break.** These control-plane events bypass the breaker so your auth/connection lifecycle is never delayed by data-path issues.

**Recovery:**

The breaker is short-lived and recovers automatically. After a brief pause, Terra cautiously tests the destination with a single request. If your server responds successfully, normal traffic resumes immediately. If it still fails, the pause re-engages. There is no manual action required. The circuit cycles until your destination is healthy or until the deliveries have used up their retries.

{% hint style="warning" %}
**Respond within 8 seconds.** If you need more time to process the data, accept the webhook immediately (return 200) and process it asynchronously. A brief timeout episode can cascade into dropped events if the circuit breaker stays open until the event's retries run out.
{% endhint %}

{% hint style="info" %}
**4xx responses on first attempts are safe.** Validation errors on a single bad payload (e.g. an unexpected field) are treated as per-message issues. Terra will not penalize your destination for an occasional 4xx, only for **persistent** 4xx across retries on the same event, which suggests the URL itself is misconfigured.
{% endhint %}

{% hint style="warning" %}
**Monitor for sustained outages.** If your destination is down long enough that an event's retries run out (this takes several hours), its delivery fails and there's no notification. New events after recovery are delivered normally. Events from the outage stay `failed` until you resend them. We recommend setting up endpoint health monitoring on your side to catch extended outages early.
{% endhint %}

## Optional: Use ping mode

For high-volume integrations or large payloads, Terra supports a **ping mode** that keeps webhook payloads small. Instead of sending the full data payload in the POST body, Terra uploads it to cloud storage and sends a lightweight summary with a pre-signed download URL.

When ping mode is enabled, your webhook receives:

```json
{
  "status": "success",
  "type": "s3_payload",
  "url": "https://presigned-download-url.example.com/...",
  "expires_in": 300
}
```

* `url`: a pre-signed link to the full data payload, hosted on Terra's infrastructure. Download it with a `GET` request.
* `expires_in`: URL validity in seconds (300 = 5 minutes).

**How to process ping mode payloads:**

1. Receive the webhook POST as usual and verify the signature.
2. Check if the `type` field is `"s3_payload"`.
3. Download the full payload from the `url` field using a `GET` request.
4. Process the downloaded JSON as you would a normal webhook payload.

```python
@app.route('/webhook', methods=['POST'])
def handle_webhook():
    data = request.get_json()

    if data.get("type") == "s3_payload":
        # Ping mode: download the full payload from the URL
        response = requests.get(data["url"])
        payload = response.json()
    else:
        # Normal mode: the full payload is in the POST body
        payload = data

    # Process payload as usual
    process(payload)
    return "", 200
```

{% hint style="info" %}
**Authentication and connection events** (auth success, deauth, etc.) are always delivered inline in the POST body, even when ping mode is enabled. Only data payloads use the S3 URL delivery.
{% endhint %}

{% hint style="info" %}
**To enable ping mode**, open your webhook destination on the [Connections page](https://dashboard.tryterra.co/dashboard/connections), set **Delivery mode** to **Ping**, and save. It is configured per destination and does not require any changes to your webhook URL. If you do not see a Delivery mode option, contact Terra support and we'll enable it for you.
{% endhint %}

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how resends work.
* [Health data events](/unified-api/receiving-data-updates): handle the data payloads your endpoint receives.


# SQL database (Postgres, MySQL)

Create a database user so Terra can write events to your Postgres or MySQL database, and read the tables it creates.

SQL databases are easy to set up and often the go-to choices for less abstracted storage solutions. Terra supports Postgres and MySQL. This page covers creating a database user for Terra, adding the destination, and the tables Terra writes.

## Before you begin

* A Postgres or MySQL database reachable from Terra's servers.

{% hint style="warning" %}
**Security:** Do not open your database to the entire internet. Restrict inbound connections to Terra's IP addresses listed on the [Destinations page](/destinations/setting-up-data-destinations#ip-allowlist), and use a strong, unique password for the database user.
{% endhint %}

## Create a database user

Create a user with enough permissions to create tables and have read & write access within those tables. You can execute the scripts below based on your database:

{% tabs %}
{% tab title="Postgres" %}
Terra creates tables under a dedicated `terra` schema. Your database user needs the following permissions:

```sql
CREATE USER terra_user WITH PASSWORD 'your_password';
GRANT CONNECT ON DATABASE your_database_name TO terra_user;
CREATE SCHEMA IF NOT EXISTS terra;
GRANT USAGE ON SCHEMA terra TO terra_user;
GRANT CREATE ON SCHEMA terra TO terra_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA terra
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO terra_user;
```

{% endtab %}

{% tab title="MySQL" %}

```sql
CREATE USER 'terra_user'@'%' IDENTIFIED BY 'your_password';
GRANT CREATE, SELECT, INSERT, UPDATE, DELETE ON your_database_name.* TO 'terra_user'@'%';
```

{% endtab %}
{% endtabs %}

## Add the destination in Terra

On the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard, click **Add New** and add the SQL destination. Enter your database host, port, database name, username, and password, then click **Apply**.

## What Terra writes

Terra creates three tables in your database:

{% tabs %}
{% tab title="Postgres" %}
All tables are created under the `terra` schema (e.g. `terra.terra_users`).

```sql
CREATE TABLE terra.terra_users (
    user_id VARCHAR(36) PRIMARY KEY,
    reference_id TEXT DEFAULT NULL,
    created_at TEXT NOT NULL,
    granted_scopes TEXT DEFAULT NULL,
    provider TEXT NOT NULL
);

CREATE TABLE terra.terra_data_payloads (
    payload_id VARCHAR(255) PRIMARY KEY,
    user_id VARCHAR(36) NOT NULL,
    data_type TEXT NOT NULL,
    created_at TEXT NOT NULL,
    payload_url TEXT NOT NULL,
    start_time TEXT DEFAULT NULL,
    end_time TEXT DEFAULT NULL,
    FOREIGN KEY (user_id) REFERENCES terra.terra_users(user_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE terra.terra_other_payloads (
    user_id VARCHAR(36) NOT NULL,
    payload_type TEXT DEFAULT NULL,
    created_at TEXT NOT NULL,
    payload_url TEXT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES terra.terra_users(user_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);
```

{% endtab %}

{% tab title="MySQL" %}
Tables are created in the database you specify (no schema prefix).

```sql
CREATE TABLE terra_users (
    user_id VARCHAR(36) PRIMARY KEY,
    reference_id TEXT DEFAULT NULL,
    created_at TEXT NOT NULL,
    granted_scopes TEXT DEFAULT NULL,
    provider TEXT NOT NULL
);

CREATE TABLE terra_data_payloads (
    payload_id VARCHAR(255) PRIMARY KEY,
    user_id VARCHAR(36) NOT NULL,
    data_type TEXT NOT NULL,
    created_at TEXT NOT NULL,
    payload_url TEXT NOT NULL,
    start_time TEXT DEFAULT NULL,
    end_time TEXT DEFAULT NULL,
    FOREIGN KEY (user_id) REFERENCES terra_users(user_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE terra_other_payloads (
    user_id VARCHAR(36) NOT NULL,
    payload_type TEXT DEFAULT NULL,
    created_at TEXT NOT NULL,
    payload_url TEXT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES terra_users(user_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);
```

{% endtab %}
{% endtabs %}

**How Terra uses each table:**

* **`terra_users`**: a row is created (or updated) for each user on `auth_success` events.
* **`terra_data_payloads`**: each data event (activity, sleep, body, etc.) gets a row. The actual data payload is stored in a Terra-managed bucket, and the `payload_url` column contains a pre-signed download link.
* **`terra_other_payloads`**: all non-data events (deauth, access revoked, etc.) get a row, with the full event payload available via `payload_url`.

{% hint style="warning" %}
The `payload_url` links are **pre-signed URLs that expire after 10 minutes**. Download the payload promptly after it is inserted. If you need to re-fetch expired data, use the [REST API](/unified-api/requesting-historical-data) to request it again.
{% endhint %}

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how retries work.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra delivers.


# Supabase

Connect a Supabase project through OAuth so Terra writes events to its Postgres tables and storage bucket.

[Supabase](https://supabase.com/) combines [storage buckets](https://supabase.com/docs/guides/storage) for raw payloads and [Postgres tables](https://supabase.com/docs/guides/database/tables) for structured metadata in one platform. Terra connects to your project through OAuth and provisions everything it needs.

## Before you begin

* A Supabase account. You can pick an existing project or create one while connecting.

## Add the destination in Terra

Terra integrates with Supabase via OAuth. Everything is provisioned automatically:

1. On the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard, click **Add New** and select **Supabase**.
2. You'll be redirected to Supabase to authorize Terra.
3. Select an existing project or create a new one.
4. Terra automatically provisions the following in your project:
   * A **`terra-payloads`** storage bucket for raw data files
   * Access via your project's **service role key** for secure write operations
   * Three database tables (see [What Terra writes](#what-terra-writes) below)

No manual setup is required.

## What Terra writes

### Database tables

Terra creates three tables in your Supabase project's Postgres database:

```sql
CREATE TABLE terra_users (
    user_id TEXT PRIMARY KEY,
    reference_id TEXT,
    created_at TIMESTAMPTZ,
    granted_scopes TEXT,
    provider TEXT,
    state TEXT
);

CREATE TABLE terra_data_payloads (
    payload_id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    data_type TEXT,
    created_at TIMESTAMPTZ,
    start_time TIMESTAMPTZ,
    end_time TIMESTAMPTZ,
    FOREIGN KEY (user_id) REFERENCES terra_users(user_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE terra_misc_payloads (
    payload_id TEXT PRIMARY KEY,
    user_id TEXT NOT NULL,
    data_type TEXT,
    payload_type TEXT,
    created_at TIMESTAMPTZ,
    FOREIGN KEY (user_id) REFERENCES terra_users(user_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);
```

* **`terra_users`**: created or updated on authentication events. The `state` column tracks the user's lifecycle (`active`, `deauth`, `user_reauth`, etc.).
* **`terra_data_payloads`**: one row per record inside a payload's `data` array, not one row per webhook event. An event covering 30 days of `daily` data writes 30 rows. Rows are keyed on `payload_id`, so each distinct `summary_id` gets its own row. Records without a `summary_id` (`daily`, for example) are keyed by the user's provider account (not the Terra `user_id`), data type and `start_time` date instead, so several records for the same provider account, type and day collapse into one row (last write wins). Records carrying no `start_time` or `end_time` are written to neither this table nor the storage bucket.
* **`terra_misc_payloads`**: non-data events (deauth, access revoked, etc.).

Foreign keys use `ON DELETE CASCADE` and `ON UPDATE CASCADE`, so deleting or updating a user automatically propagates to their payloads.

### Storage bucket

Raw JSON payloads are uploaded to the `terra-payloads` bucket with the path:

```
{data_type}/{payload_id}.json
```

For example: `activity/3a4b5c6d7e8f9012.json`

## Row Level Security (RLS)

RLS is **disabled** on the Terra tables by default. This is intentional:

* Terra writes data using a **service role key**, which bypasses RLS regardless.
* Enabling RLS without policies would block your client-side reads (Supabase defaults to deny-all when RLS is on with no policies).

You're free to enable RLS and add your own policies to control how your frontend or users access the data. Terra's writes will continue to work regardless.

## User lifecycle

Terra automatically manages user state transitions in your Supabase tables:

* **Re-authentication**: when a user re-authenticates, Terra migrates their existing payloads to the new user ID and updates all foreign key references.
* **Deauthentication**: when a user disconnects, Terra deletes their record from `terra_users` (cascading to all payload rows) and removes their files from the storage bucket.

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how retries work.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra delivers.


# Cloud storage (S3, GCS, Azure Blob)

Write raw Terra payloads to an AWS S3, Google Cloud Storage or Azure Blob bucket, and find files by date, type and user.

Terra can dump raw data payloads directly into your cloud storage bucket. Supported providers: **AWS S3**, **Google Cloud Storage (GCS)**, and **Azure Blob Storage**. This page covers granting Terra write access, adding the destination, and the folder layout Terra writes.

## Before you begin

* A bucket in AWS S3 or GCS, or a container in Azure Blob Storage.

## Grant Terra write access

{% tabs %}
{% tab title="AWS S3" %}
Give Terra a role in your AWS account, or an access key. For a role, see [Role-based access](#role-based-access).

For an access key, [create an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html) and [attach a policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html) granting `s3:PutObject` on your bucket. Terra needs nothing else: it never reads or deletes objects. If the bucket is encrypted with a customer-managed KMS key, also allow `kms:GenerateDataKey` and `kms:Decrypt` on that key.
{% endtab %}

{% tab title="GCS" %}
[Create a service account](https://developers.google.com/workspace/guides/create-credentials#service-account) and grant it the **Storage Object Admin** role (`roles/storage.objectAdmin`) on your target bucket. This role is required because Terra overwrites existing files on redelivery, which needs both `storage.objects.create` and `storage.objects.delete` permissions. Download the JSON credentials file.

You can grant the role via the console or with:

```bash
gsutil iam ch serviceAccount:YOUR_SA@YOUR_PROJECT.iam.gserviceaccount.com:objectAdmin gs://YOUR_BUCKET
```

{% endtab %}

{% tab title="Azure Blob" %}
Generate a [SAS URL](https://learn.microsoft.com/en-us/azure/storage/common/storage-sas-overview) for your storage account that grants write access to your target container.
{% endtab %}
{% endtabs %}

## Add the destination in Terra

On the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard, click **Add New**, add the storage destination, and enter the details for your provider:

| Provider   | Details                                                                   |
| ---------- | ------------------------------------------------------------------------- |
| AWS S3     | **Bucket name**, **region**, **Access Key ID**, and **Secret Access Key** |
| GCS        | **Bucket name** and the credentials JSON file                             |
| Azure Blob | **SAS URL** and **container name**                                        |

### Terra checks access when you save

When you create an S3 destination, turn one on, or change its configuration, Terra first writes a small file, `terra-connection-check.json`, to the root of your bucket. It uses the same credentials as deliveries, whether that is a role or an access key. Every check overwrites that same key.

```json
{
  "type": "connection_check",
  "message": "Terra sent this to check it can deliver here. You can ignore or delete it.",
  "checked_at": "2026-11-10T09:30:00Z"
}
```

If the write fails, Terra doesn't save the change and names the setting to fix. Through the API, that is a `400` with an entry such as `config.bucket: this bucket doesn't exist`. If Terra can't reach AWS, the request returns a `503` and you can retry it. A destination saved turned off isn't checked, and a `?dry_run=true` request writes nothing.

If something in your account processes every new object in the bucket, have it skip `terra-connection-check.json`.

## Role-based access

Instead of an access key, you can let Terra assume a role in your AWS account. Terra assumes it through its own AWS identity, so there is no key to store or rotate. You create the role from Terra's CloudFormation template, and it can only write objects to the one bucket you name. It can't read, list or delete anything.

{% hint style="info" %}
The dashboard will offer this option soon. Until then, set it up through the [admin API](https://docs.tryterra.co/reference/admin-api/overview). The examples below use [`terra admin-api`](https://docs.tryterra.co/developer-tools/terra-cli/raw-requests) from the Terra CLI.
{% endhint %}

### Get your setup values

`GET /environments/{dev_id}/unified-api/destination-types` returns `aws_role_setup` on the `s3` type. It needs the `destinations:read` scope.

```bash
terra admin-api /environments/<DEV_ID>/unified-api/destination-types --jq '.data[] | select(.type == "s3") | .aws_role_setup'
```

| Field                 | What it is                                                                                                                 |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `external_id`         | The External ID Terra assumes your role with. It is unique to your Terra account and the same for every environment in it. |
| `terra_principal_arn` | Terra's AWS principal, the only identity your role trusts.                                                                 |
| `template_url`        | Terra's CloudFormation template.                                                                                           |
| `quick_create_url`    | Opens the AWS console's **Quick create stack** page with the template, `ExternalId` and `TerraPrincipalArn` filled in.     |

If `aws_role_setup` is missing, role-based access isn't available for that environment. Use an access key instead.

### Create the role

1. Sign in to the AWS account that owns the bucket, and open `quick_create_url`.
2. Set `BucketName` to your bucket's name. Leave `QueueArn` empty.
3. If the bucket is encrypted with a customer-managed KMS key, set `KmsKeyArn` to the key's ARN. Otherwise leave it empty.
4. Leave `ExternalId` and `TerraPrincipalArn` as they are. Terra only assumes the role with your account's External ID, so a stack with a different value won't work.
5. Acknowledge that the stack creates an IAM role, and create the stack.
6. When the stack is created, copy `RoleArn` from its **Outputs** tab. Paste it rather than typing it: the role's name ends in the UUID from the stack's ID, as in `arn:aws:iam::<ACCOUNT_ID>:role/TerraByoCloud-<STACK_UUID>`.

Terra only accepts roles named `TerraByoCloud-<name>`, which is what the template creates. To deploy the template with your own tooling, use `template_url` with the same parameters.

### Add the role to the destination

Put the `RoleArn` in the destination's `config` as `role_arn`, when you create the destination or with a `PATCH`. Both need the `destinations:write` scope.

```bash
terra admin-api /environments/<DEV_ID>/unified-api/destinations -X POST --body '{
  "type": "s3",
  "config": {
    "bucket": "<BUCKET_NAME>",
    "region": "<REGION>",
    "role_arn": "<ROLE_ARN>"
  }
}'
```

A destination uses a role or an access key, not both. To move an existing destination from an access key to the role, clear the key in the same request:

```bash
terra admin-api /environments/<DEV_ID>/unified-api/destinations/<DESTINATION_ID> -X PATCH --body '{
  "config": {
    "role_arn": "<ROLE_ARN>",
    "access_key_id": null,
    "secret_access_key": null
  }
}'
```

To go back to an access key, send both keys with `"role_arn": null`. Saving runs the [access check](#terra-checks-access-when-you-save), so a role Terra can't assume or write with is refused before any delivery uses it.

## What Terra writes

All cloud storage destinations use the same folder structure:

```
2022-03-16/
  {event_type}/
    {user_id}-{timestamp}.json       # Auth/misc events
  {data_type}/
    {user_id}-{start_time}.json      # Data events (activity, sleep, etc.)
```

For example:

```
2022-03-16/auth/abc123-2026-03-12T14:30:00Z.json
2022-03-16/activity/abc123-2026-03-12T06:00:00Z.json
2022-03-16/sleep/abc123-2026-03-11T22:00:00Z.json
```

* **Data events** (activity, sleep, body, etc.) are placed under a folder named after the data type, with each file named `{user_id}-{start_time}.json`.
* **Auth and other events** are placed under a folder named after the event type, with each file named `{user_id}-{timestamp}.json`.
* The `2022-03-16` prefix corresponds to the API version.

{% hint style="info" %}
**FIT files (S3 only):** For activity data that includes raw FIT files, Terra uploads both the JSON payload and the original `.fit` file alongside it (e.g. `2022-03-16/activity/abc123-2026-03-12T06:00:00Z.fit`).
{% endhint %}

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how retries work.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra delivers.


# Queues (SQS, Kafka)

Deliver Terra events to an AWS SQS queue or a Kafka topic, with each message linking to the full payload.

Terra can deliver events straight into an AWS SQS queue or publish them to a Kafka topic. Each message is small and carries a pre-signed link to the full data payload. This page covers setting up each service, adding the destination, and the message format.

## Before you begin

* An [AWS SQS](https://aws.amazon.com/sqs/) queue, or an [Apache Kafka](https://kafka.apache.org/) cluster with a topic for Terra to publish to.

## Set up AWS SQS

AWS SQS is a managed queuing system that lets Terra deliver events straight into your existing queue, minimising disruptions when ingesting data into your server.

Give Terra a role in your AWS account, or an access key. For a role, see [Role-based access](#role-based-access).

For an access key, [create an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html) and attach a policy granting:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "sqs:SendMessage"
      ],
      "Resource": "arn:aws:sqs:your-region:your-account-id:your-queue-name"
    }
  ]
}
```

If the queue is encrypted with a customer-managed KMS key, also allow `kms:GenerateDataKey` and `kms:Decrypt` on that key. If Terra uploads payloads to your own S3 bucket, the user also needs `s3:PutObject` on that bucket.

## Set up Kafka

Terra connects to Kafka using **SASL PLAIN** authentication over **TLS**. Create SASL credentials for Terra on your cluster.

Terra auto-creates the topic if it doesn't exist. This requires `auto.create.topics.enable=true` on the broker. If it is disabled, create the topic manually first.

## Add the destination in Terra

On the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard, click **Add New**, add the queue destination, and enter the details for your service:

| Service | Details                                                                                    |
| ------- | ------------------------------------------------------------------------------------------ |
| AWS SQS | **Queue URL**, **Access Key ID**, **Secret Access Key**, and **region**                    |
| Kafka   | **Broker host and port**, **username and password** (SASL credentials), and **topic name** |

### Terra checks SQS access when you save

When you create an SQS destination, turn one on, or change its configuration, Terra first sends one test message to the queue. It uses the same credentials as deliveries, whether that is a role or an access key. If Terra uploads the destination's payloads to your own S3 bucket, it writes a small file, `terra-connection-check.json`, to the root of that bucket before sending the message. Every check overwrites that same key.

The message and the file have the same body:

```json
{
  "type": "connection_check",
  "message": "Terra sent this to check it can deliver here. You can ignore or delete it.",
  "checked_at": "2026-11-10T09:30:00Z"
}
```

If your consumer handles every message on the queue, have it delete `connection_check` messages without processing them. They carry no `url`.

If the check fails, Terra doesn't save the change and names the setting to fix. Through the API, that is a `400` with an entry such as `config.queue: this queue doesn't exist in this region`. If Terra can't reach AWS, the request returns a `503` and you can retry it. A destination saved turned off isn't checked, and a `?dry_run=true` request sends nothing.

## Role-based access

Instead of an access key, you can let Terra assume a role in your AWS account. Terra assumes it through its own AWS identity, so there is no key to store or rotate. You create the role from Terra's CloudFormation template. It can only send messages to the one queue you name, and write objects to your own S3 bucket if Terra uploads payloads there. It can't read, list or delete anything.

{% hint style="info" %}
The dashboard will offer this option soon. Until then, set it up through the [admin API](https://docs.tryterra.co/reference/admin-api/overview). The examples below use [`terra admin-api`](https://docs.tryterra.co/developer-tools/terra-cli/raw-requests) from the Terra CLI.
{% endhint %}

### Get your setup values

`GET /environments/{dev_id}/unified-api/destination-types` returns `aws_role_setup` on the `sqs` type. It needs the `destinations:read` scope.

```bash
terra admin-api /environments/<DEV_ID>/unified-api/destination-types --jq '.data[] | select(.type == "sqs") | .aws_role_setup'
```

| Field                 | What it is                                                                                                                 |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `external_id`         | The External ID Terra assumes your role with. It is unique to your Terra account and the same for every environment in it. |
| `terra_principal_arn` | Terra's AWS principal, the only identity your role trusts.                                                                 |
| `template_url`        | Terra's CloudFormation template.                                                                                           |
| `quick_create_url`    | Opens the AWS console's **Quick create stack** page with the template, `ExternalId` and `TerraPrincipalArn` filled in.     |

If `aws_role_setup` is missing, role-based access isn't available for that environment. Use an access key instead.

### Create the role

1. Sign in to the AWS account that owns the queue, and open `quick_create_url`.
2. Set `QueueArn` to your queue's ARN, `arn:aws:sqs:<REGION>:<ACCOUNT_ID>:<QUEUE_NAME>`.
3. If Terra uploads payloads to your own S3 bucket, set `BucketName` to that bucket. Otherwise leave it empty.
4. If the queue or bucket is encrypted with a customer-managed KMS key, set `KmsKeyArn` to the key's ARN. Otherwise leave it empty.
5. Leave `ExternalId` and `TerraPrincipalArn` as they are. Terra only assumes the role with your account's External ID, so a stack with a different value won't work.
6. Acknowledge that the stack creates an IAM role, and create the stack.
7. When the stack is created, copy `RoleArn` from its **Outputs** tab. Paste it rather than typing it: the role's name ends in the UUID from the stack's ID, as in `arn:aws:iam::<ACCOUNT_ID>:role/TerraByoCloud-<STACK_UUID>`.

Terra only accepts roles named `TerraByoCloud-<name>`, which is what the template creates. To deploy the template with your own tooling, use `template_url` with the same parameters.

### Add the role to the destination

Put the `RoleArn` in the destination's `config` as `role_arn`, when you create the destination or with a `PATCH`. Both need the `destinations:write` scope.

```bash
terra admin-api /environments/<DEV_ID>/unified-api/destinations -X POST --body '{
  "type": "sqs",
  "config": {
    "queue": "https://sqs.<REGION>.amazonaws.com/<ACCOUNT_ID>/<QUEUE_NAME>",
    "region": "<REGION>",
    "role_arn": "<ROLE_ARN>"
  }
}'
```

A destination uses a role or an access key, not both. To move an existing destination from an access key to the role, clear the key in the same request:

```bash
terra admin-api /environments/<DEV_ID>/unified-api/destinations/<DESTINATION_ID> -X PATCH --body '{
  "config": {
    "role_arn": "<ROLE_ARN>",
    "access_key_id": null,
    "secret_access_key": null
  }
}'
```

To go back to an access key, send both keys with `"role_arn": null`. Saving runs the [access check](#terra-checks-sqs-access-when-you-save), so a role Terra can't assume or send with is refused before any delivery uses it.

## Message format

SQS and Kafka messages use the same format. Each message is a JSON payload containing a download URL:

```json
{
  "status": "success",
  "type": "s3_payload",
  "url": "https://storage.googleapis.com/terra-services-p-bkt-payloads/...",
  "expires_in": 600,
  "payload_reference": "bb0a8574-ac33-42e5-ae33-49aa52600b1e"
}
```

* `url`: a pre-signed link to the full data payload, hosted on Terra's infrastructure. Download it with a `GET` request; no credentials are needed.
* `expires_in`: URL validity in seconds (600 = 10 minutes).
* `payload_reference`: a unique identifier for this payload delivery.

This approach keeps message sizes small. The actual data payload must be fetched from the URL.

On Kafka, messages are published without a partition key (distributed across partitions by least-bytes balancing).

### Payloads in your own S3 bucket

For SQS, Terra can upload payloads to **your own S3 bucket** instead of its own storage. Contact Terra support to set this up.

The message format stays the same, but `url` is then the object's plain S3 address, `https://<bucket>.s3.<region>.amazonaws.com/<key>`. It is not pre-signed:

* Read it with your own AWS credentials, for example with the AWS SDK's `GetObject` on that bucket and key. A plain `GET` without credentials is refused.
* `expires_in` does not apply. The object stays in your bucket until you delete it or a lifecycle rule removes it.
* With role-based access, the role must be able to write to that bucket: set `BucketName` when you [create the role](#create-the-role).

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how retries work.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra delivers.


# MongoDB

Store full Terra payloads in your MongoDB database, with the collections, indices and document IDs Terra creates.

Terra can store health data directly in your [MongoDB](https://www.mongodb.com/) database, with full payloads stored inline (no external URLs to fetch).

## Before you begin

* A MongoDB instance reachable from Terra's servers. Terra supports both `mongodb://` and `mongodb+srv://` connection schemes.

{% hint style="warning" %}
**Security:** Restrict inbound connections to Terra's IP addresses listed on the [Destinations page](/destinations/setting-up-data-destinations#ip-allowlist). If using MongoDB Atlas, add these IPs to your [IP Access List](https://www.mongodb.com/docs/atlas/security/ip-access-list/). Use a strong, unique password and require TLS for connections.
{% endhint %}

## Create a database user

Create a database user with read/write access to your target database.

## Add the destination in Terra

On the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard, click **Add New**, add the MongoDB destination, and enter:

* **Host** (e.g. `cluster0.abc123.mongodb.net`)
* **Database name**
* **Username and password**
* **Connection scheme** (`mongodb` or `mongodb+srv`)

## What Terra writes

Terra creates collections automatically and adds indices on first write.

### Collections

| Collection     | Contents                                                 | Document ID             |
| -------------- | -------------------------------------------------------- | ----------------------- |
| `user_events`  | Auth events (auth success, deauth, access revoked, etc.) | `{user_id, event_time}` |
| `athlete`      | Athlete profile data                                     | `user_id`               |
| `activity`     | Activity data                                            | `{user_id, start_time}` |
| `body`         | Body metrics                                             | `{user_id, start_time}` |
| `daily`        | Daily summary data                                       | `{user_id, start_time}` |
| `sleep`        | Sleep data                                               | `{user_id, start_time}` |
| `nutrition`    | Nutrition data                                           | `{user_id, start_time}` |
| `menstruation` | Menstruation data                                        | `{user_id, start_time}` |

### Indices

Terra creates the following indices automatically:

* **`user_events` and `athlete`:** `user.user_id` (ascending), `user.reference_id` (ascending)
* **Data collections** (activity, body, daily, sleep, nutrition, menstruation): `metadata.start_time` (descending), `metadata.end_time` (descending)

### Document format

All documents include the full data payload inline. There are no external URLs to download. Each document includes a `user` object with the user's details.

**Data event example:**

```json
{
  "_id": { "user_id": "abc123", "start_time": "2026-03-12T06:00:00Z" },
  "user": { "user_id": "abc123", "reference_id": "your-ref", "provider": "FITBIT" },
  "metadata": { "start_time": "2026-03-12T06:00:00Z", "end_time": "2026-03-12T07:00:00Z" },
  "duration_seconds": 3600,
  "active_duration_seconds": 1800
}
```

Documents are upserted: if a document with the same ID already exists, it is replaced with the latest data.

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how retries work.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra delivers.


# Firestore

Store full Terra payloads as documents in your Google Cloud Firestore database, organised by event and data type.

Terra can store health data directly in your [Google Cloud Firestore](https://cloud.google.com/firestore) database, with full payloads stored inline as documents.

## Before you begin

* A Google Cloud project with a Firestore database.

## Create a service account

[Create a service account](https://developers.google.com/workspace/guides/create-credentials#service-account) with Firestore read/write access to your project. Download the JSON credentials file.

## Add the destination in Terra

On the [Connections page](https://dashboard.tryterra.co/dashboard/connections) in your Terra dashboard, click **Add New**, add the Firestore destination, and enter:

* **GCP Project ID**
* **Service account credentials** (JSON file upload)

## What Terra writes

Terra organises documents in a hierarchical collection structure under a `terra/2022-03-16` base path.

### Collections

| Collection path                 | Contents                                 | Document name                 |
| ------------------------------- | ---------------------------------------- | ----------------------------- |
| `terra/2022-03-16/user_events`  | Auth events (auth success, deauth, etc.) | `{user_id}-{timestamp}.json`  |
| `terra/2022-03-16/activity`     | Activity data                            | `{user_id}-{start_time}.json` |
| `terra/2022-03-16/body`         | Body metrics                             | `{user_id}-{start_time}.json` |
| `terra/2022-03-16/daily`        | Daily summary data                       | `{user_id}-{start_time}.json` |
| `terra/2022-03-16/sleep`        | Sleep data                               | `{user_id}-{start_time}.json` |
| `terra/2022-03-16/nutrition`    | Nutrition data                           | `{user_id}-{start_time}.json` |
| `terra/2022-03-16/menstruation` | Menstruation data                        | `{user_id}-{start_time}.json` |

### Document format

All documents contain the full data payload inline. There are no external URLs to download. Data event documents include the `user` object alongside the data fields.

Documents are overwritten if a document with the same name already exists (last write wins).

## Next steps

* [User authentication](/unified-api/authentication-flow): link a user's wearable so events start flowing.
* [Event delivery](/destinations/events): see what each delivery status means and how retries work.
* [Health data events](/unified-api/receiving-data-updates): process the data Terra delivers.


# Overview

Choose the Terra mobile SDK for your app to read Apple Health, Health Connect and Samsung Health, which have no web API.

Apple Health, Health Connect and Samsung Health have no web API. A Terra mobile SDK in your app reads them on the phone and sends the data to Terra, which delivers it to your destination like any other source.

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2F6AmHWjQeikbUuA4S94yh%2Fsdk_flow.png?alt=media&amp;token=421846d0-68ca-42e4-966b-a3dacd4dead8" alt="Your app reads Apple Health, Health Connect or Samsung Health on the phone, sends the data to Terra, and Terra delivers it to your destination" width="563"><figcaption><p>Data flows from the phone through Terra to your destination</p></figcaption></figure>

## Choose your SDK

Implementation details vary with your development framework or platform. Pick the guide for yours:

<table data-card-size="large" data-view="cards" data-full-width="true"><thead><tr><th align="center"></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td align="center"><strong>iOS SDK</strong></td><td><a href="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FcFdL8NtF8kHBmwAIrNUo%2Fapple_logo.png?alt=media&amp;token=7b91a5ea-df1a-4e9f-8b38-7c46bb49e076">apple_logo.png</a></td><td><a href="/mobile-sdks/ios-sdk-2">iOS SDK</a></td></tr><tr><td align="center"><strong>Android SDK</strong></td><td><a href="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fi1jbwHjs2mNj8rEuFYJH%2Fandroid_kotlin.svg?alt=media&amp;token=903aee80-7c1f-4fc3-8a51-4ed7e142b989">android_kotlin.svg</a></td><td><a href="/mobile-sdks/android-sdk-2">Android SDK</a></td></tr><tr><td align="center"><strong>React Native SDK</strong></td><td><a href="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2FWqnjo39pyL9Dsp0xSMed%2Freact_native_logo.svg?alt=media&amp;token=61ecc49c-95b8-4db7-8a89-b075b7fa0f95">react_native_logo.svg</a></td><td><a href="/mobile-sdks/react-native-sdk-2">React Native SDK</a></td></tr><tr><td align="center"><strong>Flutter SDK</strong></td><td><a href="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2F0dctvWjKHY7vVQVwtIrG%2Fflutter_logo.svg?alt=media&amp;token=3dc959ed-94f8-4510-8748-bb9ee99cb074">flutter_logo.svg</a></td><td><a href="/mobile-sdks/flutter">Flutter SDK</a></td></tr></tbody></table>

The Flutter guide covers the 1.x plugin, `terra_flutter_bridge`. The iOS, Android and React Native guides cover 2.x.

**No app of your own?** Send your users a link to [Terra Grip](/mobile-sdks/terra-grip-companion-app), Terra's app for connecting Apple Health, Health Connect and Samsung Health.

**Moving an existing app to 2.x?** Follow the upgrade guide for [iOS](/mobile-sdks/ios-migrating-to-2), [Android](/mobile-sdks/android-migrating-to-2) or [React Native](/mobile-sdks/react-native-migrating-to-2). The 1.x guides are still available for [iOS](/mobile-sdks/ios-swift), [Android](/mobile-sdks/android-kotlin) and [React Native](/mobile-sdks/react-native).

## Next steps

* [iOS SDK](/mobile-sdks/ios-sdk-2): connect Apple Health from a Swift app.
* [Android SDK](/mobile-sdks/android-sdk-2): connect Health Connect and Samsung Health from a Kotlin app.
* [React Native SDK](/mobile-sdks/react-native-sdk-2): connect both platforms from one codebase.


# iOS SDK

Install the TerraiOS SDK, connect Apple Health and keep its data flowing to Terra in the background.

This page shows how to connect Apple Health with `TerraiOS` 2.x. The SDK reads Apple Health, uploads it to Terra in the background, and delivers it to your [data destination](/destinations/setting-up-data-destinations) like any other provider.

The Swift module is `TerraSDK` and its entry point is `Terra`. Code written against 1.x does not compile against 2.0.0. If you are upgrading, read [iOS upgrade guide](/mobile-sdks/ios-migrating-to-2).

## Before you begin

* iOS 15 or later.
* A backend endpoint that mints Terra auth tokens.

## Install the SDK

{% tabs %}
{% tab title="Swift Package Manager" %}
In Xcode, add the package `https://github.com/tryterra/TerraiOS` with the rule **Up to Next Major Version** from `2.1.0`, or in `Package.swift`:

{% code title="Package.swift" %}

```swift
.package(url: "https://github.com/tryterra/TerraiOS", from: "2.1.0")
```

{% endcode %}

Link the `TerraSDK` product into your app target.
{% endtab %}

{% tab title="CocoaPods" %}
{% code title="Podfile" %}

```ruby
target 'YourApp' do
  pod 'TerraiOS', '~> 2.0'
end
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Add capabilities and Info.plist keys

Add these in **Signing & Capabilities** and in your app's `Info.plist`.

| Where        | Key                                                 | Value                                                                                                                    |
| ------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Entitlements | `com.apple.developer.healthkit`                     | `true`                                                                                                                   |
| Entitlements | `com.apple.developer.healthkit.access`              | empty array                                                                                                              |
| Entitlements | `com.apple.developer.healthkit.background-delivery` | `true`                                                                                                                   |
| Info.plist   | `NSHealthShareUsageDescription`                     | Why your app reads health data                                                                                           |
| Info.plist   | `NSHealthUpdateUsageDescription`                    | Why your app writes health data. Required even if your app never writes: App Store Connect rejects the upload without it |
| Info.plist   | `UIBackgroundModes`                                 | `fetch`                                                                                                                  |
| Info.plist   | `BGTaskSchedulerPermittedIdentifiers`               | `co.tryterra.sdk.refresh`                                                                                                |

The `TerraSDK.framework` carries its own privacy manifest (`PrivacyInfo.xcprivacy`), so Xcode's privacy report includes it.

## Mint auth tokens on your backend

The SDK links a device with a single-use auth token. Mint it on your backend with your API key, and pass your own user identifier as `reference_id`:

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

Tokens expire after three minutes and are spent on first use. Expose an endpoint in your own API that mints one for the signed-in user and returns it to the app.

## Connect Apple Health

{% code title="YourApp.swift" %}

```swift
import TerraSDK

let terra = Terra(devID: "<YOUR_DEV_ID>") {
    try await yourBackend.mintTerraToken()
}

// Once, at launch
BackgroundSync.register(terra: terra)

// When the user taps "Connect Apple Health".
// user.id is your ID for the signed-in person: the same value your backend sends as reference_id.
try await terra.connect(.health, for: .reference(user.id))
try await terra.permissions.request(read: [.daily, .sleep, .activity, .body])
```

{% endcode %}

That is the whole integration. After the permission sheet is answered, the SDK uploads on its own.

### Token provider

`connect` does not take a token. The closure you pass to [`Terra(devID:tokenProvider:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.init) supplies one, and the SDK calls it only when a new link is needed:

* the first time the device links,
* after a reinstall or a restored backup that lost the stored link,
* when a different person connects than the one the stored link was made for,
* when Terra no longer accepts the device's key and the SDK has to link again.

A normal launch for the same person restores the link from the Keychain with no network call and never calls the closure. The closure runs off the main actor and outlives the call that built it, so capture what it needs rather than a view.

If the token arrives some other way, such as a scanned QR code, pass it directly with [`connect(_:for:using:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.connect). A token passed this way always creates a fresh link.

### Name the end user

Every `connect` names the person it is for: [`.reference(id)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#enduser) with the same value your backend sends as `reference_id`, or `.anonymous` if your backend sends none. A stored link is restored only for the person it was made for:

* **The same person:** the link is restored with no network call.
* **Someone else signed in on this phone:** the SDK retires the old link the way [`disconnect()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#connection.disconnect) does, then links again with a token from the provider.
* **A link made before connections recorded their end user:** it is kept and recorded as this person's, with no network call.

This stops a second account on a shared phone from receiving the first account's link, and its data from arriving under the first account's `reference_id`. The SDK stores a salted hash of the reference, never the reference itself. The end user decides only whether the stored link may be restored: Terra still trusts only the reference inside the token, so mint the token for the same person you pass to `connect`. `disconnect()` clears the recorded end user with the link.

### Build `Terra` once, at launch

Build one `Terra` per app, at launch, and keep it. Register background sync in the same place, before the first `await`. iOS raises an exception, and the app stops, when a background task is registered after the app finishes launching.

{% code title="YourApp.swift" %}

```swift
import SwiftUI
import TerraSDK

@MainActor
final class HealthModel: ObservableObject {
    let terra = Terra(devID: "<YOUR_DEV_ID>") {
        try await YourBackend.shared.mintTerraToken()
    }

    init() {
        BackgroundSync.register(terra: terra)
    }

    func connect(userID: String) async throws {
        let connection = try await terra.connect(.health, for: .reference(userID))
        print("Terra user_id:", connection.userID)
        try await terra.permissions.request(read: [.daily, .sleep, .activity, .body])
    }
}

@main
struct YourApp: App {
    @StateObject private var model = HealthModel()

    var body: some Scene {
        WindowGroup { ContentView(model: model) }
    }
}
```

{% endcode %}

[`connection.userID`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#connection) is the Terra `user_id` that appears on your webhooks. [`terra.connections`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.connections) lists what is linked on this device.

## Request permissions

Request reads and writes in one call:

{% code title="YourApp.swift" %}

```swift
try await terra.permissions.request(
    read: [.activity, .body, .daily, .sleep],
    write: [.activity, .body]
)
```

{% endcode %}

`write: [.activity]` asks for workouts and everything a workout can carry: active energy, and walking and running, cycling and swimming distance. If your app logs only some workouts, ask for those instead with [`WorkoutScope`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#workoutscope), and leave `.activity` out of `write`. The sheet then shows only those rows:

{% code title="YourApp.swift" %}

```swift
try await terra.permissions.request(
    read: [.activity, .body, .daily, .sleep],
    write: [.body],
    workouts: [WorkoutScope(activity: .running, energy: true, distance: true)]
)
```

{% endcode %}

The categories are `daily`, `body`, `sleep`, `activity`, `nutrition`, `menstruation`, `athlete` and [`healthObservation`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#datacategory).

To read the current state:

{% code title="YourApp.swift" %}

```swift
await terra.permissions.writeStatus(for: .body)   // granted, denied or notDetermined
await terra.permissions.status(for: .body)        // may be .notDisclosed
await terra.permissions.requested                 // everything asked for so far
```

{% endcode %}

[`status(for:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#permissions.status) answers for reads. iOS never reveals whether a read was granted or denied, so on iOS it never returns `.granted` or `.denied`:

| Status          | Meaning                                                                                                    |
| --------------- | ---------------------------------------------------------------------------------------------------------- |
| `.notDisclosed` | Your app asked, and iOS will not say what the person chose. A denied read and an empty store look the same |
| `.unavailable`  | This device has no Apple Health, such as an iPad on iPadOS 16 or earlier. Hide the feature                 |
| `.unsupported`  | The device has Apple Health, but the SDK cannot read this category yet. Hide this category only            |

[`writeStatus(for:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#permissions.writestatus) answers for writes, which iOS does disclose: `.granted`, `.denied` or `.notDetermined`. For `.activity` it is `.granted` only when every type you asked to write there is granted. A workout `log` checks only the types its entries carry, so a run can still log while `writeStatus(for: .activity)` is `.denied`, for example because the person refused swimming distance.

To upload heart rate, request `body`: the heart rate and resting heart rate permissions come with it. Heart rate is uploaded on the daily route, and asking for `body` also starts the daily upload.

## Set up background delivery

[`BackgroundSync.register`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#backgroundsync.register) is the only call needed for uploads to continue while the app is closed. Call it once at launch, before the first `await`.

{% code title="YourApp.swift" %}

```swift
BackgroundSync.register(terra: terra)
```

{% endcode %}

| Parameter          | Type           | Default   | Description                                                                                                                                      |
| ------------------ | -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `terra`            | `Terra`        | required  | The client to run on each wake. Build it at launch, not inside a view                                                                            |
| `source`           | `Source`       | `.health` | The source whose HealthKit observation is restored on launch                                                                                     |
| `earliestInterval` | `TimeInterval` | `3600`    | The soonest iOS should consider waking the app again, in seconds. A floor, not a schedule: iOS decides when based on how the person uses the app |

It returns `true` when this call registered the task with iOS. `false` means one of two things:

* `co.tryterra.sdk.refresh` is missing from `BGTaskSchedulerPermittedIdentifiers`. The app is never woken for it.
* The task is already registered, for example from a second launch path. This is harmless.

The SDK also needs the `com.apple.developer.healthkit.background-delivery` entitlement. Without it HealthKit does not wake the app when new data arrives, and uploads only happen when iOS grants a background refresh slot. The SDK keeps working and reports `backgroundObservationUnavailable` on [`diagnostics.events()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#diagnostics.events).

Background delivery only runs while the phone is unlocked and has a network connection. HealthKit data is encrypted while the phone is locked.

### Run Terra from your own background task

iOS keeps one pending background refresh request per app. If your app schedules its own refresh task and also calls `register`, one of the two never runs, and the SDK reports `backgroundRefreshUnscheduled` on [`diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#diagnostics.state). Keep your task and run Terra's pass from it.

* [`registerForHostTask`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#backgroundsync.registerforhosttask): does everything `register` does at launch except ask iOS for a task. It restores the HealthKit observers a background launch needs, and cancels any refresh request the SDK left pending, so the slot is free for yours.
* [`run`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#backgroundsync.run): the same pass the SDK's own task runs. Pass its result to `setTaskCompleted(success:)`.

**Register for your task at launch.** Call `registerForHostTask` at launch, before the first `await`, instead of `BackgroundSync.register(terra:)`.

{% code title="YourApp.swift" lineNumbers="true" %}

```swift
BackgroundSync.registerForHostTask(terra: terra)
```

{% endcode %}

**Run Terra's pass from your handler.**

{% code title="YourApp.swift" lineNumbers="true" %}

```swift
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.refresh", using: .main) { task in
    scheduleNextRefresh()   // your app's own resubmit
    let work = Task { await BackgroundSync.run(terra: terra) }
    task.expirationHandler = { work.cancel() }
    Task { task.setTaskCompleted(success: await work.value) }
}
```

{% endcode %}

{% hint style="warning" %}
Register the handler with `using: .main`. A handler written in a SwiftUI `App`, or any other `@MainActor` code, is isolated to the main actor, and iOS calling it on a background queue stops the app the first time the task runs.
{% endhint %}

{% hint style="info" %}

* Cancelling the task stops the pass from starting new work. Nothing it already sent is sent again.
* `run` has 18 seconds by default. Pass `within:` with less when your own work shares the task, or more from a `BGProcessingTask`.
* `co.tryterra.sdk.refresh` can stay in `BGTaskSchedulerPermittedIdentifiers` or be removed.
* Without any background task, HealthKit wakes still upload what changed. A first sync's history and queued history requests then wait for the next foreground run or wake.
  {% endhint %}

## What syncs and when

The SDK decides when to upload:

| Trigger          | When                                                                                                                                                                       |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Permission grant | Straight after a [`permissions.request`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#permissions.request) that first asks for a category with an upload route |
| Foreground       | Each time the app becomes active, at most once every 15 minutes                                                                                                            |
| Background       | When HealthKit reports new data, and on the scheduled background refresh task                                                                                              |
| Relink           | After `connect` creates a new link, if the app had already requested access                                                                                                |

### How far back

The first sync reaches two years (730 days) back.

After every sync, we upload what has changed since the previous sync. If you log a workout today with last Tuesday's date, Terra still syncs that data.

To backfill further, [request historical data](/unified-api/requesting-historical-data) for the user from your backend with `to_webhook=true`. Terra queues the window for the device, and the next run uploads it.

### What is uploaded

| Category            | What is uploaded                                                                                                                                                                                                                    |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `daily`             | Steps, distances, energy, floors, exercise, move and stand time, and heart rate when `body` is granted, as whole local days                                                                                                         |
| `sleep`             | Sleep stages, as whole wake dates                                                                                                                                                                                                   |
| `activity`          | Workouts, including stats, events and routes                                                                                                                                                                                        |
| `body`              | Weight, height, body fat, lean mass, BMI, waist circumference, blood pressure, blood glucose, oxygen saturation, body and wrist temperature, HRV, respiratory rate, VO2 max and insulin delivery. Heart rate rides the daily upload |
| `nutrition`         | Meals and their nutrients, and water                                                                                                                                                                                                |
| `menstruation`      | Menstrual flow, and cycle events such as spotting, ovulation tests and pregnancy tests                                                                                                                                              |
| `athlete`           | Biological sex, date of birth, wheelchair use and move mode, as one snapshot                                                                                                                                                        |
| `healthObservation` | Symptoms, toothbrushing and handwashing, inhaler use, falls, blood alcohol and UV exposure                                                                                                                                          |

A run only uploads the categories your app requested.

## Read and write on the device

Local reads go straight to HealthKit and never touch the network:

{% code title="YourApp.swift" %}

```swift
let heartRate = try await terra.body.heartRate(in: .lastDays(7))
let steps = try await terra.daily.steps(in: .lastDays(7))
let sleep = try await terra.sleep.segments(in: .lastDays(1))
let workouts = try await terra.activity.workouts(in: .lastHours(24))
```

{% endcode %}

These reads need SDK 2.2.0 or later. Each takes a `TimeRange` except `athlete.profile()`. Request each read's category first:

| Read                                                                                                                  | Returns                                                                                                                                    | Category       |
| --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |
| [`daily.totals(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#dailymetrics.totals)                   | HealthKit's own total for each local day: distances, active and basal energy, flights climbed and exercise minutes                         | `daily`        |
| [`daily.intraday(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#dailymetrics.intraday)               | The energy, distance and floors samples those totals are made of                                                                           | `daily`        |
| [`body.restingHeartRate(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.restingheartrate) | HealthKit's resting heart rate, one per day                                                                                                | `body`         |
| [`body.readings(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.readings)                 | Weight, height, BMI, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate | `body`         |
| [`activity.routes(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.routes)             | Each workout's GPS track                                                                                                                   | `activity`     |
| [`activity.intensity(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.intensity)       | Speed, power and cycling cadence recorded inside workouts                                                                                  | `activity`     |
| [`nutrition.quantities(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#nutritionmetrics.quantities)   | One value per nutrient sample, not grouped into meals                                                                                      | `nutrition`    |
| [`nutrition.hydration(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#nutritionmetrics.hydration)     | Water, one sample per drink                                                                                                                | `nutrition`    |
| [`menstruation.flow(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#menstruationmetrics.flow)         | One flow value per logged day                                                                                                              | `menstruation` |
| [`menstruation.events(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#menstruationmetrics.events)     | Ovulation tests, cervical mucus and intermenstrual bleeding                                                                                | `menstruation` |
| [`athlete.profile()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#athletemetrics.profile)                | Biological sex, date of birth, wheelchair use and move mode                                                                                | `athlete`      |

In 2.2.0 and later, a [`Workout`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#workout) also carries `title`, the name the writing app gave it, and [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.availability) answers whether the device has HealthKit at all. It needs no connection, so you can call it before `connect`.

{% code title="YourApp.swift" %}

```swift
guard await terra.availability() == .available else { return }

let totals = try await terra.daily.totals(in: .lastDays(7))
let readings = try await terra.body.readings(in: .lastDays(30))
let quantities = try await terra.nutrition.quantities(in: .today)
let meals = Dictionary(grouping: quantities, by: \.foodCorrelationID)
let profile = try await terra.athlete.profile()
```

{% endcode %}

To write data your app measured itself:

{% code title="YourApp.swift" %}

```swift
let ids = try await terra.activity.log([workoutEntry])
try await terra.activity.delete(id: ids[0])
```

{% endcode %}

The write namespaces are `activity`, `body`, `daily`, `nutrition` and `sleep`. [`log`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.log) returns one `UUID` per entry, which is the only handle for deleting it later. HealthKit only lets you delete samples your app wrote.

Deleting a workout also deletes the active energy and distance logged with it, including on workouts an earlier SDK release logged. An energy or distance type the person stopped your app writing after the workout was logged stays in Apple Health.

## Disconnect a user

{% code title="YourApp.swift" %}

```swift
for connection in try await terra.connections {
    try await connection.disconnect()
}
```

{% endcode %}

[`disconnect()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#connection.disconnect) forgets the link on the device and tells Terra to stop accepting its key. To remove the user from Terra, call [deauthenticateUser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser) from your backend.

## Troubleshooting

Start with the SDK's own diagnostics:

{% code title="YourApp.swift" %}

```swift
await terra.diagnostics.state()         // healthy, quiet(since:), backgroundRestricted, pendingRetry, ...
await terra.diagnostics.lastDelivery()  // when data last reached Terra
for await event in terra.diagnostics.events() { /* typed events */ }
```

{% endcode %}

When the SDK gives up on something, such as a delivery out of retries, it sends a redacted report to Terra so support can see the device's side. The report never contains a health value.

| Symptom                                                                                                               | Cause                                                                                                                                 | Fix                                                                                                                                                                           |
| --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connect` throws [`tokenRejected`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terraerror)               | The token expired (three minutes) or was already used                                                                                 | Mint a fresh token for every link. Check the delay between minting and connecting                                                                                             |
| `connect` throws [`devIDMismatch`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terraerror)               | A different dev ID already linked on this device. A `connect` with a token is refused too                                             | Run with the original dev ID, or erase the Keychain: the record survives reinstalling the app. On a simulator, `xcrun simctl keychain <device> reset`. Use one dev ID per app |
| [`diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#diagnostics.state) is `.linkRevoked` | Terra stopped accepting this device's key, for example because another device linked the same user                                    | Call `connect(.health, for:)` again with the same end user. The token provider is called to link again                                                                        |
| `diagnostics.state()` is `.backgroundRefreshUnscheduled`                                                              | Your app submitted its own `BGAppRefreshTaskRequest` first. iOS keeps one pending refresh request per app and drops the second        | Run Terra from your own task with [`registerForHostTask`](#run-terra-from-your-own-background-task)                                                                           |
| No background uploads at all                                                                                          | `co.tryterra.sdk.refresh` missing from `BGTaskSchedulerPermittedIdentifiers`, Background fetch off, or `register` called after launch | Fix the Info.plist entry and call `register` before the first `await`. Check its return value                                                                                 |
| Uploads only when the app opens                                                                                       | Missing `healthkit.background-delivery` entitlement                                                                                   | Add the entitlement. Look for `backgroundObservationUnavailable` on `diagnostics.events()`                                                                                    |
| `diagnostics.state()` is `.quiet(since:)`                                                                             | No new data since that date                                                                                                           | Often a person who has not worn their watch. iOS does not disclose denied reads, so this is a hint, not an error                                                              |
| A category is missing in Terra                                                                                        | The app never requested it, or the person did not grant it                                                                            | Request it in `permissions.request`. iOS does not disclose denied reads, so ask the person to check **Settings > Health > Data Access & Devices**                             |

### App extensions

An app extension can read and write on grants inherited from the host app, but it cannot present a permission sheet and never syncs on its own. To share state between the host and an extension, use an App Group and a Keychain access group.

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [Planned workouts on Apple Watch](/mobile-sdks/planned-workouts-apple-watch): put plans on the user's Watch.
* [Health data events](/unified-api/receiving-data-updates): handle the data the SDK uploads.
* [Historical data requests](/unified-api/requesting-historical-data): backfill beyond the first sync.


# Android SDK

Install the terra-android SDK, connect Health Connect or Samsung Health, and keep their data flowing to Terra in the background.

This page shows how to use `terra-android` 2.x in your Android app: install it, build the client, connect a user, request permissions and set up background delivery.

The SDK reads the health store, uploads it to Terra in the background, and delivers it to your [data destination](/destinations/setting-up-data-destinations) like any other provider. It supports:

* Health Connect
* Samsung Health, through Health Connect or directly with the Samsung add-on. See [Samsung Health](/mobile-sdks/samsung-health).

{% hint style="info" %}
This page covers `terra-android` 2.x, whose Kotlin package is `co.tryterra.sdk`. For 1.x, read [Android SDK 1.x](/mobile-sdks/android-kotlin). To move an existing app, read [Android upgrade guide](/mobile-sdks/android-migrating-to-2).
{% endhint %}

## Before you begin

* `minSdk` 28 (Android 9) or later. The Samsung Health add-on needs 29 (Android 10).
* `compileSdk` 36 or later and Android Gradle Plugin 8.9.1 or later, required by the SDK's Health Connect dependency.
* Health Connect on the device.
* A backend endpoint that mints Terra auth tokens. See [Generate an auth token](#generate-an-auth-token).

## Install the SDK

### Add the dependency

* Inside the dependencies section of your `build.gradle.kts` file, add the following line of code.

{% code title="app/build.gradle.kts" %}

```kotlin
dependencies {
    implementation("co.tryterra:terra-android:2.2.1")
}
```

{% endcode %}

* You can find the latest version number on [Maven Central](https://central.sonatype.com/artifact/co.tryterra/terra-android/).

### Sync your project

Sync your project with Gradle by clicking on the "**Sync Project with Gradle Files**" button in the toolbar. This downloads the SDK and makes it available to your project.

{% hint style="danger" %}
**Do not add `terra-android` 2.x to an app that still uses the 1.x React Native or Flutter wrapper (`terra-react` or `terra-flutter`).**
{% endhint %}

### Configure health permissions

The SDK's own manifest declares no health permission and no component. Your app declares exactly what it uses.

{% tabs %}
{% tab title="Health Connect" %}
**1. Declare the Health Connect permissions**

For each category your app requests, declare every permission in its row below, and nothing else. Health Connect never grants a permission that is missing from your manifest, and Google Play rejects apps that declare data types they do not use. A permission shared by two of your categories is declared once.

| Category       | Permissions (each prefixed with `android.permission.health.`)                                                                                                                                                                                                                                                                                                                                  |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DAILY`        | `READ_STEPS`, `READ_DISTANCE`, `READ_FLOORS_CLIMBED`, `READ_ELEVATION_GAINED`, `READ_ACTIVE_CALORIES_BURNED`, `READ_TOTAL_CALORIES_BURNED`, `READ_BASAL_METABOLIC_RATE`, `READ_HEART_RATE`, `READ_RESTING_HEART_RATE`, `READ_HEART_RATE_VARIABILITY`                                                                                                                                           |
| `ACTIVITY`     | `READ_EXERCISE`, `READ_STEPS`, `READ_DISTANCE`, `READ_SPEED`, `READ_POWER`, `READ_FLOORS_CLIMBED`, `READ_ELEVATION_GAINED`, `READ_ACTIVE_CALORIES_BURNED`, `READ_TOTAL_CALORIES_BURNED`, `READ_BASAL_METABOLIC_RATE`, `READ_HEART_RATE`, `READ_HEART_RATE_VARIABILITY`                                                                                                                         |
| `SLEEP`        | `READ_SLEEP`, `READ_HEART_RATE`, `READ_RESTING_HEART_RATE`, `READ_HEART_RATE_VARIABILITY`, `READ_OXYGEN_SATURATION`, `READ_RESPIRATORY_RATE`                                                                                                                                                                                                                                                   |
| `BODY`         | `READ_WEIGHT`, `READ_HEIGHT`, `READ_BODY_FAT`, `READ_LEAN_BODY_MASS`, `READ_BONE_MASS`, `READ_BODY_WATER_MASS`, `READ_BODY_TEMPERATURE`, `READ_BASAL_BODY_TEMPERATURE`, `READ_SKIN_TEMPERATURE`, `READ_BLOOD_GLUCOSE`, `READ_BLOOD_PRESSURE`, `READ_OXYGEN_SATURATION`, `READ_VO2_MAX`, `READ_RESPIRATORY_RATE`, `READ_BASAL_METABOLIC_RATE`, `READ_HEART_RATE`, `READ_HEART_RATE_VARIABILITY` |
| `NUTRITION`    | `READ_NUTRITION`, `READ_HYDRATION`                                                                                                                                                                                                                                                                                                                                                             |
| `MENSTRUATION` | `READ_MENSTRUATION`, `READ_INTERMENSTRUAL_BLEEDING`, `READ_OVULATION_TEST`, `READ_CERVICAL_MUCUS`, `READ_SEXUAL_ACTIVITY`                                                                                                                                                                                                                                                                      |

For example, an app that requests only `DAILY` declares:

{% code title="AndroidManifest.xml" lineNumbers="true" %}

```xml
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.READ_DISTANCE" />
<!-- ...and the other eight DAILY permissions -->

<!-- Optional: keep syncing while the app is closed -->
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
<!-- Optional: read more than 30 days back on the first sync -->
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />
```

{% endcode %}

[`HealthConnectPermissions.readPermissions(categories)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#healthconnectpermissions.readpermissions) returns the same list, for a test that keeps your manifest in step with the categories you request.

If you write to Health Connect, [`HealthConnectPermissions.writePermissions`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#healthconnectpermissions.writepermissions) is the matching write set. Writing `ACTIVITY` needs `WRITE_EXERCISE`, `WRITE_ACTIVE_CALORIES_BURNED` and `WRITE_DISTANCE`, because a workout's energy and distance are separate records in Health Connect.

**2. Add the privacy policy screen, declared twice**

Health Connect opens your privacy policy screen with a different action below and above Android 14, so declare both:

{% code title="AndroidManifest.xml" lineNumbers="true" %}

```xml
<activity android:name=".PermissionsRationaleActivity" android:exported="true">
    <intent-filter>
        <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
    </intent-filter>
</activity>

<activity-alias
    android:name=".ViewPermissionUsageActivity"
    android:exported="true"
    android:targetActivity=".PermissionsRationaleActivity"
    android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
    <intent-filter>
        <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
        <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
    </intent-filter>
</activity-alias>
```

{% endcode %}

Without the alias, Android 14 and above refuse every read with "Incorrect health permission state", including reads that were granted. The screen must show the same privacy policy as your Play listing.

**3. Allow network access and Health Connect visibility**

The SDK needs `INTERNET` to link and upload. On Android 13 and below, Health Connect is a separate app, and without the package query the SDK cannot see it and reports it as unavailable.

{% code title="AndroidManifest.xml" lineNumbers="true" %}

```xml
<uses-permission android:name="android.permission.INTERNET" />

<queries>
    <package android:name="com.google.android.apps.healthdata" />
</queries>
```

{% endcode %}

{% hint style="info" %}
WorkManager, which the SDK uses, merges `WAKE_LOCK`, `ACCESS_NETWORK_STATE`, `RECEIVE_BOOT_COMPLETED` and `FOREGROUND_SERVICE` into your manifest. None of them needs a Play declaration. Do not remove them.
{% endhint %}

{% hint style="warning" %}
**Apply for Health Connect access.** Before release, submit the Health Connect declaration in the Play Console. Select only the health features your permissions support, and give one sentence per data type on how it benefits the user.
{% endhint %}
{% endtab %}

{% tab title="Samsung Health" %}
Samsung Health's data reaches the SDK through Health Connect once the person lets Samsung Health share with Health Connect. Follow the Health Connect tab for that.

To read Samsung Health's own store directly, add the `terra-android-samsung` add-on. It needs Samsung's partner approval and Samsung's own SDK, which your app packages. Follow [Samsung Health](/mobile-sdks/samsung-health) for the approval, the dependencies and the store registration.
{% endtab %}
{% endtabs %}

## Initialize the SDK

The first step is to **build the Terra client.**

Build it **once**, in `Application.onCreate`, and keep it for the life of the process. Background runs start your process with no activity in it, so a client built in a screen does not exist when they arrive.

### Import `Terra` and `BackgroundSync`

{% code title="YourApp.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.sdk.Terra
import co.tryterra.sdk.background.BackgroundSync
```

{% endcode %}

### Build the Terra client

Call [`Terra(...)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.invoke) with the following arguments:

* `context`: Any context. The SDK keeps the application context.
* `devId`: Your **Developer ID** provided by Terra.
* `tokenProvider`: A suspend function that returns a **one-time authentication token** from your backend. See [Generate an auth token](#generate-an-auth-token) below.

Then register background sync with [`BackgroundSync.register`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#backgroundsync.register). See [Set up background delivery](#set-up-background-delivery).

{% code title="YourApp.kt" lineNumbers="true" %}

```kotlin
import android.app.Application
import android.util.Log
import co.tryterra.sdk.Terra
import co.tryterra.sdk.background.BackgroundSync

class YourApp : Application() {
    lateinit var terra: Terra

    override fun onCreate() {
        super.onCreate()
        terra = Terra(
            this,
            devId = BuildConfig.TERRA_DEV_ID,
            tokenProvider = { yourBackend.mintTerraToken() },
        )
        if (!BackgroundSync.register(this, terra)) {
            Log.w("Terra", "Background sync was refused; nothing is scheduled")
        }
    }
}
```

{% endcode %}

{% hint style="warning" %}
Name the `tokenProvider` argument. The factory's last parameter is `stores`, so a trailing lambda binds there instead, and the client has no token provider at all.
{% endhint %}

## Connect a user

Once the client exists, you can create a connection by calling `connect()`, then request permissions with `permissions.request()` to show the permission screen.

### Call `connect()`

Call [`connect()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connect) with the following arguments:

* `source`: `Source.HEALTH` for Health Connect, or `Source.SAMSUNG_HEALTH` for Samsung Health directly, with the add-on.
* `forUser`: The person the connection is for. [`EndUser.Reference(id)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#enduser) with the same value your backend sends as `reference_id`, or `EndUser.Anonymous` if your backend sends none.
* `token` (optional): A token you already hold, for example from a QR code. A token passed this way always creates a fresh link.

`connect` returns the connection. [`connection.userId`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#storedconnection) is the Terra `user_id` that appears on your webhooks.

### Call `permissions.request()`

Call [`permissions.request()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.request) with the categories to read and write, and a [`PermissionLauncher`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissionlauncher) to present the sheet. The categories are `DAILY`, `BODY`, `SLEEP`, `ACTIVITY`, `NUTRITION` and `MENSTRUATION`. `connect` never shows a permission screen on its own.

Create the launcher in `onCreate`, before anything that suspends: Android refuses the registration once the activity is started.

{% tabs %}
{% tab title="Health Connect" %}
{% code title="ConnectActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.sdk.DataCategory
import co.tryterra.sdk.EndUser
import co.tryterra.sdk.Source
import co.tryterra.sdk.permissions.PermissionLauncher

class ConnectActivity : ComponentActivity() {
    private val terra get() = (application as YourApp).terra
    private lateinit var launcher: PermissionLauncher

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launcher = terra.permissions.launcher(this)

        connectButton.setOnClickListener {
            lifecycleScope.launch {
                val connection = terra.connect(Source.HEALTH, EndUser.Reference(signedInUser.id))
                Log.i("Terra", "user_id ${connection.userId}")
                val granted = terra.permissions.request(
                    read = setOf(DataCategory.DAILY, DataCategory.SLEEP, DataCategory.ACTIVITY),
                    launcher = launcher,
                )
            }
        }
    }

    override fun onDestroy() {
        launcher.unregister()
        super.onDestroy()
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Samsung Health" %}
Follow [Samsung Health](/mobile-sdks/samsung-health) first. Samsung Health has its own permission sheet, so it has its own launcher, reached through [`terra.on(Source.SAMSUNG_HEALTH)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.on).

{% code title="ConnectActivity.kt" lineNumbers="true" %}

```kotlin
// in onCreate
samsungLauncher = terra.on(Source.SAMSUNG_HEALTH).permissions.launcher(this)

// on tap
terra.connect(Source.SAMSUNG_HEALTH, EndUser.Reference(signedInUser.id))
terra.on(Source.SAMSUNG_HEALTH).permissions.request(
    read = setOf(DataCategory.DAILY, DataCategory.SLEEP, DataCategory.ACTIVITY),
    launcher = samsungLauncher,
)
```

{% endcode %}
{% endtab %}
{% endtabs %}

### What `permissions.request()` returns

What the sheet granted, narrowed to this call. Check it rather than assuming the person said yes.

When the request reads anything, the sheet also asks for background read and history read, if your manifest declares them.

{% hint style="info" %}
**Request `DAILY` even if you show no step data.** Heart rate is uploaded on the daily route.
{% endhint %}

### The same person keeps their link

A stored link is restored only for the person it was made for. A normal launch for the same person restores it with no network call and never calls `tokenProvider`. When someone else signs in on the same phone, the SDK retires the old link the way [`terra.disconnect`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.disconnect) does and links again, so their data does not arrive under the first person's `reference_id`. A link made before connections recorded their end user is kept and recorded as this person's.

The SDK stores a salted hash of the reference, never the reference itself. Terra still trusts only the reference inside the token, so mint the token for the same person you pass to `connect`.

### Write permissions and workout scopes

`write = setOf(DataCategory.ACTIVITY)` asks for the exercise session, active calories and distance. If your app logs workouts without energy or distance, leave `ACTIVITY` out of `write` and pass [`WorkoutScope`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#workoutscope)s in `workouts` instead. The sheet then asks only for what the scopes name:

{% code title="ConnectActivity.kt" lineNumbers="true" %}

```kotlin
terra.permissions.request(
    read = setOf(DataCategory.DAILY, DataCategory.SLEEP, DataCategory.ACTIVITY),
    workouts = setOf(WorkoutScope(WorkoutActivity.Running, distance = true)),
    launcher = launcher,
)
```

{% endcode %}

[`writeStatus(ACTIVITY)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.writestatus) is `GRANTED` only when every type you asked to write there is granted. A workout `log` checks only the grants its entries use, so a run without energy can still log while `writeStatus(ACTIVITY)` is `DENIED`.

### Check permissions without prompting

{% code lineNumbers="true" %}

```kotlin
terra.permissions.status(DataCategory.SLEEP)    // GRANTED, DENIED, NOT_DETERMINED, ...
terra.permissions.writeStatus(DataCategory.ACTIVITY)
terra.permissions.backgroundReadStatus()
terra.permissions.historyReadStatus()
terra.permissions.requested()                   // everything asked for so far
```

{% endcode %}

GPS routes need `READ_EXERCISE_ROUTES`, which Health Connect only grants in Settings or through its own route consent screen. The SDK never asks for it. If your app holds it and requests `ACTIVITY`, routes are uploaded with workouts. In the background they are usually withheld unless the app also holds background read.

## Generate an auth token

`tokenProvider` needs a **single-use token** to link the device to Terra. It is called only while `connect` makes a new link:

* the first time the device links,
* after a reinstall, or anything else that cleared the app's stored link,
* when a different person connects than the one the stored link was made for,
* when Terra no longer accepts the device's key and the SDK has to link again.

Generate the token with `POST https://api.tryterra.co/v2/auth/generateAuthToken` from **your backend server**, with your Terra `x-api-key` and `dev-id` in the headers and your own user identifier as `reference_id`. Then return it to your app from your own API.

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

{% hint style="warning" %}

* Tokens expire after three minutes and are spent on first use.
* **DO NOT** expose your API key in your mobile app. Make this call **only** from your **backend**.
  {% endhint %}

## Validate the connection

To check that a connection is still working on the client side, use [`diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#diagnostics.state). [`terra.connections()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connections) lists the connections on the device, with the `userId` of each.

{% code title="YourApp.kt" lineNumbers="true" %}

```kotlin
when (val state = terra.diagnostics.state()) {
    is DiagnosticsState.LinkRevoked -> Unit                    // connect again with the same end user
    is DiagnosticsState.BackgroundRestricted -> state.reason   // OEM_RESTRICTED, BACKGROUND_READ_DENIED, TICKS_NOT_RUNNING, ...
    is DiagnosticsState.BackgroundRefreshUnscheduled -> Unit   // register was never called
    is DiagnosticsState.Quiet -> state.since
    else -> Unit
}
```

{% endcode %}

{% hint style="info" %}
**Always validate the connection on app start.** If `diagnostics.state()` is `LinkRevoked`, Terra stopped accepting this device's key, for example because another device linked the same user. Call `connect(Source.HEALTH, forUser)` again with the same end user. The token provider is called to link again.

When the SDK gives up on something, it sends a redacted report to Terra so support can see the device's side. The report never contains a health value.
{% endhint %}

## Set up background delivery

Background delivery allows data to be synced even when your app is not in the foreground. There is no call that starts a sync: after the permission sheet is answered, the SDK uploads on its own, in the foreground and in the background.

[`BackgroundSync.register`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#backgroundsync.register) from [Initialize the SDK](#initialize-the-sdk) schedules it. Call it once, from `Application.onCreate`. Calling it again from another launch path costs nothing.

* `context`: Any context. The SDK keeps the application context.
* `terra`: The client to run on each background tick.
* `processExit` (optional): [`ProcessExitPolicy`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#processexitpolicy). Defaults to `KEEP_PROCESS`. `EXIT_WHEN_IDLE` ends your process after a background tick when nothing else is running in it, which stops some OEM battery managers from freezing it. Use it only if your process exists to sync: the SDK cannot see push handlers, bound services or content providers you run.

It returns `false` when another client with the same dev ID already owns background sync and does not serve this client's health stores. Nothing is scheduled in that case, so check the return value.

What it schedules:

* A periodic run every 15 minutes, the platform's minimum, whenever the device has a network connection.
* A run each time the app comes to the foreground, at most once every 15 minutes.
* Each run stops itself after 8 minutes and leaves the rest for the next one.

Declare `READ_HEALTH_DATA_IN_BACKGROUND` in your manifest so the permission sheet asks for background read. Without it granted, background runs read nothing and `diagnostics.state()` reports `BackgroundRestricted(BACKGROUND_READ_DENIED)`.

### OEM battery restrictions

{% hint style="warning" %}
Some manufacturers stop background work regardless of the permissions an app holds. On Xiaomi, Redmi and POCO phones, for example, apps install with Autostart off, and swiping the app away cancels every scheduled job until the app is opened again. The phone needs both Autostart **on** and the battery setting at **No restrictions**.

Show the person one screen after they connect, with a button to the right settings page:

```kotlin
BackgroundSetup.oemSetupIntents(context).firstOrNull()?.let { activity.startActivity(it) }
```

The list is most specific first, and only contains screens that exist on the device. Start them from an `Activity`. Do not declare `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` or `QUERY_ALL_PACKAGES`: Play restricts both, and the SDK does not need them.
{% endhint %}

From here, health data events reach your data destination, such as a webhook, automatically.

You can also [request historical data](/unified-api/requesting-historical-data) from your backend to backfill.

Check out the [Android SDK reference](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2) for details about all the functions in the SDK.

## What syncs and when

The SDK decides when to upload:

| Trigger          | When                                                                               |
| ---------------- | ---------------------------------------------------------------------------------- |
| Permission grant | Straight after a `permissions.request` that grants a category with an upload route |
| Foreground       | Each time the app comes to the foreground, at most once every 15 minutes           |
| Background       | The periodic WorkManager run, every 15 minutes at best                             |
| Relink           | After `connect` creates a new link, if the app had already requested access        |

`connect` does not upload anything. On a first link nothing has been requested yet, so no data moves until the permission sheet is answered. When the app already had access, a run starts after the link, and `connect` returns without waiting for it.

### How far back

The first sync reaches two years (730 days) back, newest first: today arrives in the first upload, and the history fills in behind it across as many runs as it takes. Health Connect only serves the last 30 days unless the app holds `READ_HEALTH_DATA_HISTORY`.

After that, every run uploads what changed since the last successful one. The SDK reads Health Connect's change log, which lists what was **written** since the last sync, not the date the data is about. A workout added today for last Tuesday still syncs, and the day it belongs to is uploaded again.

To backfill further, [request historical data](/unified-api/requesting-historical-data) for the user from your backend with `to_webhook=true`. Terra queues the window for the device, and the next run uploads it.

### What is uploaded

| Category       | What is uploaded                                                                                                                                                                                                                                        |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DAILY`        | Steps, heart rate, resting heart rate, active energy, distance, floors and day totals, as whole local days                                                                                                                                              |
| `SLEEP`        | Sleep sessions and stages                                                                                                                                                                                                                               |
| `ACTIVITY`     | Workouts with stats, laps and segments, speed, power and cadence, and GPS routes when the route permission is held                                                                                                                                      |
| `BODY`         | Weight, height, body fat, lean mass, bone mass, body water mass, basal metabolic rate, blood pressure, blood glucose, oxygen saturation, body, basal and skin temperature, HRV (RMSSD), respiratory rate and VO2 max. Heart rate rides the daily upload |
| `NUTRITION`    | Nutrition records and hydration                                                                                                                                                                                                                         |
| `MENSTRUATION` | Menstrual flow, and cycle events such as ovulation tests, cervical mucus, intermenstrual bleeding and sexual activity                                                                                                                                   |

Health Connect has no record for the athlete profile, so Android uploads none.

A run only uploads the categories your app requested. A permission another part of your app holds is not uploaded unless this client asked for its category.

The SDK never reports deletions. A record deleted in Health Connect stays in Terra. To remove a user's data, deauthenticate the user from your backend.

## Read and write on the device

Local reads go to Health Connect and never touch the network:

{% code lineNumbers="true" %}

```kotlin
terra.body.heartRate(TimeRange.LastHours(6))
terra.daily.steps(TimeRange.Today)
terra.sleep.segments(TimeRange.LastDays(7))
terra.activity.workouts(TimeRange.Between(from, to))
```

{% endcode %}

Reading a category your app has not requested throws [`TerraError.AuthorizationNotDetermined`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terraerror) rather than returning an empty list. [`daily.steps`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.steps) returns one total per day per writing app: do not add them up.

These reads need SDK 2.2.1 or later. Each takes a `TimeRange` and checks the category in the last column:

| Read                                                                                                                 | Returns                                                                                                                               | Category            |
| -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| [`daily.totals`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.totals)                   | Health Connect's own total for each local day: walking and running distance, active and basal energy, and floors climbed              | `DAILY`             |
| [`daily.intraday`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.intraday)               | The active energy, distance and floors records those totals are made of                                                               | `DAILY`             |
| [`body.restingHeartRate`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.restingheartrate) | Health Connect's resting heart rate                                                                                                   | `DAILY`, not `BODY` |
| [`body.readings`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.readings)                 | Weight, height, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate | `BODY`              |
| [`activity.routes`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.routes)             | Each session's GPS track, where the person allowed it                                                                                 | `ACTIVITY`          |
| [`activity.intensity`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.intensity)       | Speed, power and cycling cadence. Health Connect does not link them to a session                                                      | `ACTIVITY`          |
| [`nutrition.quantities`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#nutritionmetrics.quantities)   | One value per nutrient a meal recorded                                                                                                | `NUTRITION`         |
| [`nutrition.hydration`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#nutritionmetrics.hydration)     | Water, one record per drink                                                                                                           | `NUTRITION`         |
| [`menstruation.flow`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#menstruationmetrics.flow)         | One flow value per logged day                                                                                                         | `MENSTRUATION`      |
| [`menstruation.events`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#menstruationmetrics.events)     | Ovulation tests, cervical mucus and intermenstrual bleeding                                                                           | `MENSTRUATION`      |

Except `daily.totals`, each of these reads asks Health Connect only for its own record types, so a refused grant throws `TerraError.PermissionDenied` even when another type in the same category is allowed. `daily.totals` leaves a refused metric out instead. In 2.2.1 and later, a [`Workout`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#workout) also carries `title`, and [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.availability) answers whether Health Connect is installed and current, with no connection needed.

{% code lineNumbers="true" %}

```kotlin
if (terra.availability() != StoreAvailability.Available) return

val totals = terra.daily.totals(TimeRange.LastDays(7))
val readings = terra.body.readings(TimeRange.LastDays(30))
val meals = terra.nutrition.quantities(TimeRange.Today).groupBy { it.foodCorrelationId }
val flow = terra.menstruation.flow(TimeRange.LastDays(90))
```

{% endcode %}

To write data your app measured itself, use `log` on the `activity`, `body`, `daily`, `nutrition` and `sleep` namespaces, and `delete` with the handle it returns. Deleting a workout also deletes the active calories and distance logged with it.

{% hint style="warning" %}
If the person revokes a write grant after your app used it, a correction that drops that field and a `delete` both succeed, but the earlier record of that type stays in Health Connect until the grant is restored. For example, revoking the active calories grant after a run with energy was logged leaves that energy record behind when the run is deleted.
{% endhint %}

## Disconnect a user

{% code lineNumbers="true" %}

```kotlin
terra.disconnect(Source.HEALTH)
```

{% endcode %}

`disconnect` forgets the link on the device and tells Terra to stop accepting its key. To remove the user from Terra, call [deauthenticateUser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser) from your backend.

## Troubleshooting

| Symptom                                                                                                                                  | Cause                                                                                              | Fix                                                                                                                                                                                    |
| ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| App crashes with missing `co.tryterra.terra` classes                                                                                     | `terra-react` or `terra-flutter` 1.x and `terra-android` 2.x in one app                            | Remove `terra-android` 2.x until you move off the old wrapper                                                                                                                          |
| `connect` throws `TokenRejected`                                                                                                         | The token expired (three minutes) or was already used                                              | Mint a fresh token for every link                                                                                                                                                      |
| `connect` or `permissions.request` throws `HealthDataUnavailable`                                                                        | Health Connect is missing or needs an update                                                       | Send the person to install or update Health Connect from Google Play                                                                                                                   |
| [`permissions.launcher`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.launcher) throws `TerraError.Platform` | It was called after the activity started, or after it was destroyed                                | Call `permissions.launcher(this)` in `onCreate`, before anything that suspends, `connect` included                                                                                     |
| Every read fails with "Incorrect health permission state"                                                                                | The Android 14 rationale `activity-alias` is missing                                               | Add both rationale declarations from [Configure health permissions](#configure-health-permissions)                                                                                     |
| `BackgroundRestricted(OEM_RESTRICTED)`                                                                                                   | The manufacturer's battery manager is stopping background work                                     | Show [`BackgroundSetup.oemSetupIntents`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#backgroundsetup.oemsetupintents) to the person                                   |
| `BackgroundRestricted(TICKS_NOT_RUNNING)`                                                                                                | Background runs are scheduled but have not run for 48 hours                                        | Usually an OEM restriction. Same fix                                                                                                                                                   |
| [`BackgroundRefreshUnscheduled`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#diagnosticsstate)                          | `BackgroundSync.register` was never called, or returned `false`                                    | Call it from `Application.onCreate` and check its return value                                                                                                                         |
| `LinkRevoked`                                                                                                                            | Terra stopped accepting this device's key, for example because another device linked the same user | Call `connect(Source.HEALTH, forUser)` again with the same end user. The token provider is called to link again                                                                        |
| First sync only reaches 30 days                                                                                                          | `READ_HEALTH_DATA_HISTORY` not declared or not granted                                             | Declare it, and check [`permissions.historyReadStatus()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.historyreadstatus)                                  |
| A category is missing in Terra                                                                                                           | The app never requested it, its permission is not in the manifest, or the person did not grant it  | Check [`permissions.status(category)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.status), and declare every permission in its row of the manifest table |

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [Samsung Health](/mobile-sdks/samsung-health): read Samsung Health directly with the add-on.
* [Health data events](/unified-api/receiving-data-updates): handle the data the SDK uploads.
* [Historical data requests](/unified-api/requesting-historical-data): backfill beyond the first sync.


# React Native SDK

Install @tryterra/react-native, connect Apple Health, Health Connect or Samsung Health, and keep their data flowing to Terra in the background.

This page shows how to use `@tryterra/react-native` 2.x to connect Apple Health on iOS, and Health Connect or Samsung Health on Android: install the package, create the client, connect a user and set up background delivery.

{% hint style="info" %}
This page covers `@tryterra/react-native` 2.x. For `terra-react` 1.x, read [React Native SDK 1.x](/mobile-sdks/react-native). To move an existing app, read [React Native upgrade guide](/mobile-sdks/react-native-migrating-to-2).
{% endhint %}

## Before you begin

* React Native 0.81 or later, with the New Architecture.
* iOS 15.1 or later.
* Android `minSdkVersion` 28 and `compileSdkVersion` 36.
* A backend endpoint that mints Terra auth tokens. See [Generate an auth token](#generate-an-auth-token).

## Install the SDK

1. Install the [`@tryterra/react-native` package](https://www.npmjs.com/package/@tryterra/react-native) using npm (`npm install @tryterra/react-native@2.2.1`). The package carries the iOS SDK and resolves the Android SDK from Maven Central, so there is nothing else to install.
2. Complete the following iOS and/or Android setup.

{% tabs %}
{% tab title="iOS Setup" %}

1. In your terminal, cd to your `/ios` folder, and run `pod install` to install all the dependencies.
2. **Add Capabilities** in **Signing & Capabilities**:
   1. HealthKit > HealthKit Background Delivery
   2. Background Modes > Background fetch
3. **Add the following keys to your Info.plist:**

**Option 1: add the keys in Xcode.**

1. Go to the `/ios` directory of your project, open the `.xcworkspace` in Xcode.
2. Go to **Info.plist**, and add the following keys and values:

| Key                                             | Value                                                                            |
| ----------------------------------------------- | -------------------------------------------------------------------------------- |
| `TerraDevID`                                    | Your **Developer ID** provided by Terra                                          |
| Privacy - Health Share Usage Description        | Why your app reads health data                                                   |
| Privacy - Health Update Usage Description       | Why your app writes health data. App Store Connect rejects the upload without it |
| Permitted background task scheduler identifiers | `co.tryterra.sdk.refresh`                                                        |

**Option 2: edit Info.plist directly.**

{% code title="Info.plist" lineNumbers="true" %}

```xml
<key>TerraDevID</key>
<string>YOUR_DEV_ID</string>
<key>NSHealthShareUsageDescription</key>
<string>We read your health data to show your activity and sleep.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>We save your workouts to Apple Health.</string>
<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>co.tryterra.sdk.refresh</string>
</array>
```

{% endcode %}

4. **Bootstrap the SDK at launch.** Call `TerraReactNative.bootstrap()` first thing in `application(_:didFinishLaunchingWithOptions:)`, before React Native starts:

{% code title="AppDelegate.swift" lineNumbers="true" %}

```swift
import TerraReactNative

func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
  TerraReactNative.bootstrap()
  // ... start React Native as usual
  return true
}
```

{% endcode %}

{% hint style="info" %}
The SDK client is built here, natively, because a background wake from HealthKit starts your app without a JavaScript runtime, and iOS only accepts a background task registered before launch finishes. `bootstrap()` reads `TerraDevID` from `Info.plist`, builds the client and registers background sync. Calling it more than once does nothing.

Without it, every call rejects with `bridge.not_bootstrapped`, and the error's `details.line` names the line to add.
{% endhint %}
{% endtab %}

{% tab title="Android Setup" %}

1. **Add your Developer ID** inside `<application>`:

{% code title="android/app/src/main/AndroidManifest.xml" lineNumbers="true" %}

```xml
<meta-data
  android:name="co.tryterra.sdk.DEV_ID"
  android:value="YOUR_DEV_ID" />
```

{% endcode %}

There is no code to add. The package's `androidx.startup` initializer builds the client before `Application.onCreate`. If your app removes WorkManager's default initializer to configure WorkManager itself, call `TerraReactNative.bootstrap(this)` at the end of `Application.onCreate` instead.

2. **Declare the Health Connect permissions.** Add one `<uses-permission>` for each Health Connect type your `permissions.request` reads. For `read: ['activity', 'daily', 'sleep']`:

{% code title="android/app/src/main/AndroidManifest.xml" lineNumbers="true" %}

```xml
<uses-permission android:name="android.permission.health.READ_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" />
<uses-permission android:name="android.permission.health.READ_HEART_RATE_VARIABILITY" />
<uses-permission android:name="android.permission.health.READ_STEPS" />
<uses-permission android:name="android.permission.health.READ_SLEEP" />
<uses-permission android:name="android.permission.health.READ_EXERCISE" />
<uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.READ_TOTAL_CALORIES_BURNED" />
<uses-permission android:name="android.permission.health.READ_BASAL_METABOLIC_RATE" />
<uses-permission android:name="android.permission.health.READ_DISTANCE" />
<uses-permission android:name="android.permission.health.READ_FLOORS_CLIMBED" />
<uses-permission android:name="android.permission.health.READ_ELEVATION_GAINED" />
<uses-permission android:name="android.permission.health.READ_POWER" />
<uses-permission android:name="android.permission.health.READ_SPEED" />
<uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION" />
<uses-permission android:name="android.permission.health.READ_RESPIRATORY_RATE" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />
<uses-permission android:name="android.permission.health.READ_HEALTH_DATA_HISTORY" />

<queries>
  <package android:name="com.google.android.apps.healthdata" />
</queries>
```

{% endcode %}

{% hint style="warning" %}
Health Connect refuses the whole permission sheet if the request asks for one type the manifest does not declare. The [Android SDK guide](/mobile-sdks/android-sdk-2) lists the types behind every category.
{% endhint %}

3. **Add the permission rationale.** Health Connect links to your privacy policy from its permission screen. Add the rationale filter to your main activity, and the alias that Android 14 and later require:

{% code title="android/app/src/main/AndroidManifest.xml" lineNumbers="true" %}

```xml
<activity android:name=".MainActivity" android:exported="true">
  <!-- ... your existing filters ... -->
  <intent-filter>
    <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
  </intent-filter>
</activity>

<activity-alias
  android:name=".ViewPermissionUsageActivity"
  android:exported="true"
  android:targetActivity=".MainActivity"
  android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
  <intent-filter>
    <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
    <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
  </intent-filter>
</activity-alias>
```

{% endcode %}

{% hint style="warning" %}
Without the alias, Android 14 and later refuse every read.
{% endhint %}
{% endtab %}
{% endtabs %}

## Initialize the SDK

The first step is to **create the Terra client.**

Create it **once**, **at module scope** (e.g. in a `terra.ts` file), and import it wherever you need it. The native side of the SDK is already running from [Install the SDK](#install-the-sdk), so the client only connects your JavaScript to it.

### Import the Terra SDK

{% code title="terra.ts" lineNumbers="true" %}

```typescript
import { createTerra } from '@tryterra/react-native';
```

{% endcode %}

### Create the Terra client

Call `createTerra()` with the following options:

* `tokenProvider`: A function that returns a promise of a **one-time authentication token** from your backend. See [Generate an auth token](#generate-an-auth-token) below.
* `tokenTimeoutMs` (optional): How long the native side waits for `tokenProvider`. Defaults to 30 seconds. After that the connect rejects with `bridge.token_timeout` on iOS and `token_provider_failed` on Android.

Find more details in the SDK Reference: [createTerra](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2)

{% code title="terra.ts" lineNumbers="true" %}

```typescript
import { createTerra } from '@tryterra/react-native';

export const terra = createTerra({
  tokenProvider: () => api.terraToken(), // your backend's token endpoint
});
```

{% endcode %}

## Connect a user

Once the client exists, you can create a connection by calling `connect()`, then request permissions with `permissions.request()` to show the permission screen.

### Call `connect()`

Import `EndUser` from `@tryterra/react-native` and call [`connect()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2) with the following arguments:

* `source`: `'health'` (Apple Health on iOS, Health Connect on Android) or `'samsungHealth'` (Samsung Health directly, Android only).
* `endUser`: The person the connection is for. `EndUser.reference(id)` with the same value your backend sends as `reference_id`, or `EndUser.anonymous` if your backend sends none.
* `options.token` (optional): A token you already hold, for example from a QR code or a deep link. A token passed this way always creates a fresh link.

### Call `permissions.request()`

Call [`permissions.request()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2) with the categories to read and write. The categories are `activity`, `body`, `daily`, `sleep` and `nutrition`. With SDK 2.2.1 or later you can also request `menstruation`, and `athlete` on iOS. `connect` never shows a permission screen on its own.

{% tabs %}
{% tab title="Apple Health (iOS)" %}
{% code title="ConnectButton.tsx" lineNumbers="true" %}

```tsx
import { EndUser, TerraError } from '@tryterra/react-native';
import { terra } from './terra';

const connectHealth = async () => {
  try {
    await terra.connect('health', EndUser.reference(user.id));
    await terra.permissions.request({ read: ['activity', 'body', 'daily', 'sleep'] });
  } catch (error) {
    if (error instanceof TerraError) {
      console.error('Connection failed:', error.code);
    }
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Health Connect (Android)" %}
{% code title="ConnectButton.tsx" lineNumbers="true" %}

```tsx
import { EndUser, TerraError } from '@tryterra/react-native';
import { terra } from './terra';

const connectHealth = async () => {
  try {
    await terra.connect('health', EndUser.reference(user.id));
    const granted = await terra.permissions.request({
      read: ['activity', 'body', 'daily', 'sleep'],
    });
    console.log('Granted:', granted);
  } catch (error) {
    if (error instanceof TerraError) {
      console.error('Connection failed:', error.code);
    }
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Samsung Health (Android)" %}
Follow [Samsung Health](/mobile-sdks/samsung-health) first, then set `terraSamsungHealth=true` in `android/gradle.properties`.

{% code title="ConnectButton.tsx" lineNumbers="true" %}

```tsx
import { EndUser, TerraError } from '@tryterra/react-native';
import { terra } from './terra';

const connectSamsung = async () => {
  try {
    await terra.connect('samsungHealth', EndUser.reference(user.id));
    await terra.permissions.request({ read: ['daily', 'sleep'] }, 'samsungHealth');
  } catch (error) {
    if (error instanceof TerraError) {
      console.error('Connection failed:', error.code);
    }
  }
}
```

{% endcode %}

Without `terraSamsungHealth=true`, `'samsungHealth'` rejects with `health_data_unavailable`. To read Samsung Health's data through Health Connect instead, connect `'health'`, once the person lets Samsung Health share with Health Connect.
{% endtab %}
{% endtabs %}

### What `permissions.request()` resolves with

* **Android**: what the sheet granted, narrowed to this call. Check it rather than assuming the person said yes.
* **iOS**: `undefined`. iOS never reveals whether a read was granted.

When the request reads anything, the Android sheet also asks for background read and history read, if your manifest declares them. Check them afterwards with `terra.permissions.backgroundReadStatus()` and `terra.permissions.historyReadStatus()`.

{% hint style="info" %}
**Heart rate needs `body` on iOS.** Heart rate is uploaded on the daily route. On iOS its permission comes with `body`, so request `body` to upload it. On Android it comes with `daily`.
{% endhint %}

### The same person keeps their link

A stored link is restored only for the person it was made for. A normal launch for the same person restores it with no network call and never calls `tokenProvider`. When someone else signs in on the same phone, the SDK retires the old link and links again, so their data does not arrive under the first person's `reference_id`.

## Generate an auth token

`tokenProvider` needs a **single-use token** to link the device to Terra. It is called only while `connect` makes a new link: the first time the device links, after a reinstall, when a different person connects, or when Terra no longer accepts the device's key.

Generate the token with `POST https://api.tryterra.co/v2/auth/generateAuthToken` from **your backend server**, with your Terra `x-api-key` and `dev-id` in the headers and your own user identifier as `reference_id`. Then return it to your app from your own API.

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

{% hint style="warning" %}

* Tokens expire after three minutes and are spent on first use.
* **DO NOT** expose your API key in your mobile app. Make this call **only** from your **backend**.
  {% endhint %}

## Validate the connection

To check that a connection is still working on the client side, use [`diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2). `terra.connections()` lists the connections on the device, with the `userId` of each.

{% code title="app.tsx" lineNumbers="true" %}

```typescript
const state = await terra.diagnostics.state();        // { state: 'healthy' }, { state: 'quiet', since }, ...
const last = await terra.diagnostics.lastDelivery();   // when data last reached Terra
const stop = terra.diagnostics.events((event) => console.log(event));
```

{% endcode %}

{% hint style="info" %}
**Always validate the connection on app start.** If `diagnostics.state()` is `{ state: 'linkRevoked' }`, Terra stopped accepting this device's key. Call `connect` again with the same end user to link again.

`diagnostics.events` reports everything the SDK does as it happens, and never carries a health value. Call the returned function to stop listening.
{% endhint %}

## Set up background delivery

Background delivery allows data to be synced even when your app is not brought to the foreground. There is no call that starts a sync: after the permission sheet is answered, the SDK uploads on its own, in the foreground and in the background.

{% tabs %}
{% tab title="Apple Health" %}
Background sync is registered by `TerraReactNative.bootstrap()` from [Install the SDK](#install-the-sdk). Check that:

1. `bootstrap()` runs in `didFinishLaunchingWithOptions`.
2. `co.tryterra.sdk.refresh` is in `BGTaskSchedulerPermittedIdentifiers`.
3. The HealthKit Background Delivery capability is on.

`terra.background.isRegistered()` answers whether it was registered.
{% endtab %}

{% tab title="Android (Health Connect & Samsung)" %}
Background sync is scheduled through WorkManager by the package's startup initializer. Keep WorkManager's default initializer, or call `TerraReactNative.bootstrap(this)` at the end of `Application.onCreate`.

Declare `READ_HEALTH_DATA_IN_BACKGROUND` in your manifest so the permission sheet asks for background read. `terra.background.isRegistered()` answers whether background sync was registered.
{% endtab %}
{% endtabs %}

From here, health data events reach your data destination, such as a webhook, automatically.

You can also [request historical data](/unified-api/requesting-historical-data) from your backend to backfill.

Check out the [React Native SDK reference](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2) for details about all the functions in the SDK.

## Read and write on the device

Local reads go to Apple Health or Health Connect and never touch the network. Each takes a `TimeRange`:

{% code lineNumbers="true" %}

```typescript
const heartRate = await terra.body.heartRate({ kind: 'lastHours', hours: 6 });
const steps = await terra.daily.steps({ kind: 'today' });
const sleep = await terra.sleep.segments({ kind: 'lastDays', days: 7 });
const workouts = await terra.activity.workouts({ kind: 'lastDays', days: 1 });
```

{% endcode %}

These reads need SDK 2.2.1 or later:

| Read                                                                                                               | Returns                                                                                                                               | Platforms                                      |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| [`daily.totals`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.totals)                   | The store's own total for each local day: distance, active and basal energy, flights climbed, and exercise minutes on iOS             | Both                                           |
| [`daily.intraday`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.intraday)               | The energy, distance and floors records those totals are made of                                                                      | Both. Basal energy iOS only                    |
| [`body.restingHeartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.restingheartrate) | The store's resting heart rate                                                                                                        | Both. Needs `daily` on Android                 |
| [`body.readings`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.readings)                 | Weight, height, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate | Both. BMI and wrist temperature iOS only       |
| [`activity.routes`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.routes)             | Each workout's GPS track                                                                                                              | Both                                           |
| [`activity.intensity`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.intensity)       | Speed, power and cycling cadence                                                                                                      | Both. No `workoutId` on Android                |
| [`nutrition.quantities`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#nutrition.quantities)   | One value per nutrient, not grouped into meals                                                                                        | Both                                           |
| [`nutrition.hydration`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#nutrition.hydration)     | Water, one sample per drink, in millilitres                                                                                           | Both                                           |
| [`menstruation.flow`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#menstruation.flow)         | One flow value per logged day                                                                                                         | Both                                           |
| [`menstruation.events`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#menstruation.events)     | Ovulation tests, cervical mucus and intermenstrual bleeding                                                                           | Both                                           |
| [`athlete?.profile()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#athlete.profile)          | Biological sex, date of birth, wheelchair use and move mode                                                                           | iOS. `terra.athlete` is `undefined` on Android |

Request the category before you read it. A read of a category your app never requested rejects with `authorization_not_determined`. In 2.2.1 and later, a `Workout` also carries `title`, and [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#availability) answers whether the device can serve `'health'` at all, before `connect`.

{% code lineNumbers="true" %}

```typescript
const availability = await terra.availability();
if (availability.kind !== 'available') return;

await terra.permissions.request({
  read: terra.athlete ? ['daily', 'nutrition', 'menstruation', 'athlete'] : ['daily', 'nutrition', 'menstruation'],
});
const totals = await terra.daily.totals({ kind: 'lastDays', days: 7 });
const quantities = await terra.nutrition.quantities({ kind: 'lastDays', days: 7 });
const flow = await terra.menstruation.flow({ kind: 'lastDays', days: 90 });
const profile = await terra.athlete?.profile();
```

{% endcode %}

To write data your app measured itself, use `log` on the `activity`, `body`, `daily`, `nutrition` and `sleep` namespaces, and [`delete`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#delete) with the ID it returns.

## Disconnect a user

{% code lineNumbers="true" %}

```typescript
await terra.disconnect();
```

{% endcode %}

`disconnect` forgets the link on the device and tells Terra to stop accepting its key. To remove the user from Terra, call [deauthenticateUser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser) from your backend.

## Handle errors

Every rejection is a `TerraError` with a stable `code`, a `retryable` flag, and a `details` object:

{% code lineNumbers="true" %}

```typescript
import { EndUser, TerraError } from '@tryterra/react-native';

try {
  await terra.connect('health', EndUser.reference(user.id));
} catch (error) {
  if (error instanceof TerraError && error.code === 'token_rejected') {
    // mint a fresh token and try again
  }
}
```

{% endcode %}

The [React Native SDK reference](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2) lists every code and which platform raises it.

## Troubleshooting

| Symptom                                                                                  | Cause                                                                                                                                             | Fix                                                                                                                                                     |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Every call rejects with `bridge.not_bootstrapped`                                        | iOS: `TerraReactNative.bootstrap()` is missing or `TerraDevID` is not in `Info.plist`. Android: the `co.tryterra.sdk.DEV_ID` meta-data is missing | Add the line named in `details.line`                                                                                                                    |
| `connect` rejects with `bridge.token_timeout` (iOS) or `token_provider_failed` (Android) | `tokenProvider` did not answer within `tokenTimeoutMs`, or it rejected                                                                            | Check your token endpoint. Raise `tokenTimeoutMs` if it is slow                                                                                         |
| `connect` rejects with `token_rejected`                                                  | The token expired (three minutes) or was already used                                                                                             | Mint a fresh token for every link                                                                                                                       |
| `permissions.request` rejects with `bridge.no_activity` (Android)                        | No activity was on screen to present the sheet                                                                                                    | Request permissions while your app is in the foreground                                                                                                 |
| The Android sheet closes without asking                                                  | The request reads a type the manifest does not declare                                                                                            | Declare every Health Connect type the request reads                                                                                                     |
| `diagnostics.state()` is `{ state: 'linkRevoked' }`                                      | Terra stopped accepting this device's key                                                                                                         | Call `connect` again with the same end user                                                                                                             |
| `background.isRegistered()` is `false`                                                   | The native bootstrap did not run at launch                                                                                                        | iOS: call `bootstrap()` in `didFinishLaunchingWithOptions`. Android: keep WorkManager's default initializer, or call `TerraReactNative.bootstrap(this)` |

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [Planned workouts on Apple Watch](/mobile-sdks/planned-workouts-apple-watch): put plans on the user's Watch from iOS.
* [Health data events](/unified-api/receiving-data-updates): handle the data the SDK uploads.
* [Historical data requests](/unified-api/requesting-historical-data): backfill beyond the first sync.


# Flutter SDK

Use the terra\_flutter\_bridge 1.x plugin to connect Apple Health, Health Connect and Samsung Health from a Flutter app.

This page shows how to use the Terra Flutter plugin with Android and Apple-based integrations: install it, initialize the SDK, connect a user, handle permissions and set up background delivery.

{% hint style="info" %}
This page covers the 1.x plugin, `terra_flutter_bridge`. A 2.x Flutter plugin is not available yet. For new apps on 2.x, use [iOS](/mobile-sdks/ios-sdk-2), [Android](/mobile-sdks/android-sdk-2) or [React Native](/mobile-sdks/react-native-sdk-2).
{% endhint %}

The Terra Flutter Plugin supports the following integrations:

* Samsung Health (Android)
* Health Connect (Android)
* Apple Health (iOS)

## Install the SDK

1. Install the terra flutter package using `flutter pub get terra_flutter_bridge`
2. Complete the following iOS and/or Android Setup

{% tabs %}
{% tab title="iOS Setup" %}

1. In your terminal, cd to your `/ios` folder, and run `pod install` to install all the dependencies.
2. **Add Capabilities:**
   1. Healthkit > Healthkit Background Delivery
   2. Background Modes > Background processing
   3. Background modes > Background fetch
3. **Add the following keys to your info.plist:**

**Option 1: Use Xcode**

* 1\) Go to the `/ios` directory of your project, open the `.xcworkspace` in XCode.
* 2\) Go to ***info.plist,*** and add the following keys and values:

<table><thead><tr><th width="370.9501953125">Key</th><th>Value</th></tr></thead><tbody><tr><td>Privacy - Health Share Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Privacy - Health Records Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Privacy - Health Update Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Permitted background task scheduler</td><td><code>co.tryterra.data.post.request</code></td></tr></tbody></table>

**Option 2: Edit info.plist directly**

* 1\) In your app project, go to your `/ios` folder
* 2\) Go to ***info.plist,*** and add the following tags:

{% code title="info.plist" lineNumbers="true" %}

```xml
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>co.tryterra.data.post.request</string>
</array>
  
<key>NSHealthClinicalHealthRecordsShareUsageDescription</key>
<string>Using TerraiOS to gather health data</string>

<key>NSHealthShareUsageDescription</key>
<string>Using TerraiOS as a mean of getting Health Data</string>

<key>NSHealthUpdateUsageDescription</key>
<string>Allow writing data to health kit</string>
```

{% endcode %}
{% endtab %}

{% tab title="Android Setup" %}

#### Access Samsung Health

Terra has a privileged partnership with Samsung that gives you direct access to the Samsung Health SDK, with no Health Connect intermediary. This is the recommended route for Samsung devices.

**1. Apply for Samsung Health access**

Submit your application through the [Samsung Health partnership portal](https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c).

{% hint style="info" %}
While waiting for approval, you can start development immediately using the **Health Connect** route below. Switching to Samsung direct later is a version bump with no code changes.
{% endhint %}

**2. Install the Samsung-tagged SDK**

After approval, install the Samsung-tagged version of the Terra SDK:

* **React Native:** `npm install terra-react@<samsung-version>`. Find Samsung-tagged versions on the [npm versions page](https://www.npmjs.com/package/terra-react?activeTab=versions)
* **Flutter:** Use the Samsung-tagged version of `terra_flutter_bridge`. Find versions on [pub.dev](https://pub.dev/packages/terra_flutter_bridge/versions)

**3. Add the ProGuard rule (required for release builds)**

In your `android/app/proguard-rules.pro`, add:

```proguard
-keep class com.samsung.android.** { *; }
```

Without this, R8 minification will strip Samsung SDK classes and cause runtime crashes in production.

**4. Check the requirements**

* **Samsung Health** app must be installed on the device
* **Android 28 (minSDK 28)** and above
* Enable **Developer Mode** in Samsung Health on test devices (Settings > About Samsung Health > tap version number repeatedly)
* No additional manifest or Gradle changes needed: the Terra SDK handles everything

#### Access Health Connect

**1. Grant permissions in the Health Connect app**

Give all permissions between the apps you wish to read from (e.g. **Samsung Health, Google Fit, etc**) & Health Connect.

**2. Add the Health Connect capability to your app**

In your app project, go to the `/android` folder.

Include the permission tags under the Activity you wish to link the user to when they click the **privacy policy** link in the Health Connect permission screen. Here are the steps:

1. Go to your Android App's `AndroidManifest.xml`
2. Go to your **Privacy Policy** <mark style="color:purple;">`<activity>`</mark> and include the following tags under this <mark style="color:purple;">`<activity>`</mark> tag.

"Your Android manifest needs to have an Activity that displays your app's **privacy policy**, which is your app's rationale of the requested permissions, describing how the user's data is used and handled." (Health Connect)

<pre class="language-xml" data-title="AndroidManifest.xml" data-line-numbers><code class="lang-xml"><strong>&#x3C;intent-filter>
</strong>  &#x3C;action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
 &#x3C;/intent-filter>
  
&#x3C;intent-filter>
   &#x3C;action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
  &#x3C;category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
&#x3C;/intent-filter>
</code></pre>

{% hint style="warning" %}
**Apply for Health Connect access**

Before going **live** (release), you will need to apply for permissions to access the Health Connect API with Google.

1. Use this [application form](https://developer.android.com/health-and-fitness/guides/health-connect/publish/declare-access#explain-use-data-types).
2. For each permission which you are ***not*** using, please add the following lines to your AndroidManifest.xml

{% code title="AndroidManifest.xml" overflow="wrap" %}

```xml
<uses-permission android:name="android.permission.health.READ_HEART_RATE" tools:node="remove"/>
```

{% endcode %}

with `android.permission.health.XXX` for each permission you aren't using
{% endhint %}
{% endtab %}
{% endtabs %}

## Initialize the SDK

The first step is to **initialize the Terra SDK.**

The initialization only needs to be **done once on app start**, (e.g. in your `main.dart` or an equivalent file), and every time the app is brought into the foreground. This ensures that the SDK is properly set up and ready to be used.

{% hint style="warning" %}
The SDK should be initialized every time your app is opened.

This is a necessary prerequisite for other SDK functions to run as expected.
{% endhint %}

### Import the Terra plugin

In your project, you should now be able to import function from the Terra Plugin. Here is an example:

{% code lineNumbers="true" %}

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
```

{% endcode %}

### Initialize the Terra SDK

In order to interact with the SDK, you need to call `initTerra` first.

Call `initTerra()` with the following arguments:

* `devId`: Your **Developer ID** provided by Terra.
* `referenceId`: An **ID of your choice** to identify your app user.

Here is an example:

{% code title="initializeTerra.dart" lineNumbers="true" %}

```dart
import 'package:flutter/material.dart';
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
import 'package:terra_flutter_bridge/models/enums.dart';
import 'package:terra_flutter_bridge/models/responses.dart';

void main() async {
  // Ensure that Flutter bindings are initialized
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Terra once when the app starts
  await _initializeTerra();

  // Launch your app thereafter
  runApp(Container());  // Empty container or basic widget if needed
}

Future<void> _initializeTerra() async {
  String devID = 'YOUR_DEV_ID';
  String referenceID = 'YOUR_REFERENCE_ID';

  SuccessMessage? result = await TerraFlutter.initTerra(devID, referenceID);

  if (result?.error != null) {
    throw Exception('Failed to initialise Terra ${result?.error}');
  }
  // Successfully initialised Terra!
}
```

{% endcode %}

(**N.B** This call is asynchronous, please ensure this is complete before using other SDK functions).

## Connect a user

### Call `initConnection()`

Import `initConnection` and call [`initConnection()`](https://docs.tryterra.co/reference/mobile-sdks/flutter#initconnection) with the following arguments:

* `type`: Specify the connection type: `Connection.appleHealth`, `Connection.samsung`, or `Connection.healthConnect`
* `token`: A **one-time authentication token** generated from your backend server. This ensures secure communication between your app and the Terra servers.
* `customPermissions`: A **set of permissions** that define what data you want to request (e.g., heart rate, steps). If empty, it defaults to all available permissions. See [Permissions mapping](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping) for every value and what it requests on each platform.
* `schedulerOn`:
  * **iOS**: This parameter has no effect. Background delivery is controlled by calling `Terra.setUpBackgroundDelivery()` in your AppDelegate. See [Set up background delivery](#set-up-background-delivery) below.
  * **Android**: Enables background delivery, so Terra keeps syncing while your app is in the background. See [Set up background delivery](#set-up-background-delivery) below.

{% tabs %}
{% tab title="Apple Health (iOS)" %}
{% code title="initialiseConnection.dart" lineNumbers="true" %}

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
import 'package:terra_flutter_bridge/models/enums.dart';
import 'package:terra_flutter_bridge/models/responses.dart';

Future<void> _initialiseConnection() async {
  String token = 'example_token';

  SuccessMessage? result = await TerraFlutter.initConnection(
    Connection.appleHealth,
    token,
    true,   // schedulerOn: no effect on iOS, see setUpBackgroundDelivery() below
    [],     // customPermissions: empty defaults to all
  );

  if (result?.error != null) {
    throw Exception('Failed to initialise connection ${result?.error}');
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Samsung Health (Android)" %}
{% code title="initialiseConnection.dart" lineNumbers="true" %}

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
import 'package:terra_flutter_bridge/models/enums.dart';
import 'package:terra_flutter_bridge/models/responses.dart';

Future<void> _initialiseConnection() async {
  String token = 'example_token';

  SuccessMessage? result = await TerraFlutter.initConnection(
    Connection.samsung,
    token,
    true,   // schedulerOn: enables background delivery on Android
    [],     // customPermissions: empty defaults to all
  );

  if (result?.error != null) {
    throw Exception('Failed to initialise connection ${result?.error}');
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Health Connect (Android)" %}
{% code title="initialiseConnection.dart" lineNumbers="true" %}

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
import 'package:terra_flutter_bridge/models/enums.dart';
import 'package:terra_flutter_bridge/models/responses.dart';

Future<void> _initialiseConnection() async {
  String token = 'example_token';

  SuccessMessage? result = await TerraFlutter.initConnection(
    Connection.healthConnect,
    token,
    true,   // schedulerOn: enables background delivery on Android
    [],     // customPermissions: empty defaults to all
  );

  if (result?.error != null) {
    throw Exception('Failed to initialise connection ${result?.error}');
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Apple Health permission screen.** Apple Health only shows the permission popup **once**, so calling `initConnection()` multiple times won’t trigger the popup again unless:

* you call initConnection with an expanded set of `customPermissions`
* the app is deleted and reinstalled.
  {% endhint %}

{% hint style="info" %}
**`initConnection` only needs to be called a single time.** Health Connect prohibits the permission popup to appear more than once for any given permission, so calling `initConnection` more than once will result in no action at all

The only case where it would re-appear is if:

* you call initConnection with an expanded set of `customPermissions`
* the app is deleted and reinstalled.
* a permission that was not granted to use on release by Google has been requested by the app.
  {% endhint %}

{% hint style="info" %}
**Apple Health permission screen in WebViews.**

* Apple HealthKit implements the permissions popup as a **WebView.**
* If your app is also based on a **WebView**, you will need to interrupt your **WebView**, call `initConnection`, then upon completion re-open your **WebView.**
  {% endhint %}

#### Generate an auth token

To be able to call the `initConnection()` method, you need to pass a `token` as an argument.

This `token` is a **single-use token** created to ensure the authentication endpoint for creating a connection (and connecting the SDK to Terra's servers) does not get abused.

Generate the token with this endpoint <mark style="color:orange;">`POST`</mark>`https://api.tryterra.co/v2/auth/generateAuthToken` . Make sure to call it with your Terra `x-api-key` and `dev-id` in the headers from **your backend server.** After you generate the token, provide the response to your client side using your own logic.

{% code title="CLI" %}

```bash
curl --request POST \
  --url https://api.tryterra.co/v2/auth/generateAuthToken \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>'
```

{% endcode %}

For every parameter, see the [`/auth/generateAuthToken` endpoint](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-generateauthtoken) in the API reference.

{% hint style="warning" %}

* During the development phase, it it acceptable to place this call on the **client** side, exposing your API key in your mobile app.
* For a production implementation, **DO NOT** expose your API key this way, and make sure to **only** make this call from your **backend.**
  {% endhint %}

## Validate the connection

{% hint style="info" %}
**Always validate the connection before using the SDK**

Check if a `user_id` exists right after **initializing the Terra SDK** to see if the connection still exists.

1. **Check if the User is Connected**
   1. If the function returns a user ID, the user is still connected, 🎉 keep vibing along!
   2. If the function returns <mark style="color:red;">`nil`</mark>, the user needs to reconnect.
2. **Re-connect if Needed**\
   If the connection is lost, you can call `terra.initConnection()` again to re-establish the connection.

Calling `terra.initConnection()` when the user is already connected or just needs a reconnection will re-establish the connection if necessary, and the user flow will remain uninterrupted.

On Apple Health, note that a `user_id` only tells you the connection exists on our side, not that your app still holds HealthKit access. Deleting an app clears its HealthKit authorization while the Terra connection survives, so the permission screen can still appear on the next `initConnection()` if iOS has not yet determined permissions for the current install.
{% endhint %}

## Set up background delivery

Background delivery allows data to be synced even when your app is not brought to the foreground. iOS needs a setup step in your AppDelegate; on Android it is enabled through `initConnection`.

{% tabs %}
{% tab title="Apple Health" %}

1. Go to your `/ios` folder in the **Flutter** **project**
2. Call the function `setUpBackgroundDelivery` in your AppDelegate's `didFinishLaunchingWithOptions` function

This will ensure you get updates for the user's Apple Health data automatically sent to your destination.

{% code title="AppDelegate.swift" lineNumbers="true" %}

```swift
import UIKit
import Flutter
import TerraiOS

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
      Terra.setUpBackgroundDelivery()
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
```

{% endcode %}

{% hint style="success" %}

## iOS Background Delivery Behaviour:

* Data will still be triggered if the **app** **is** **killed** (with much lower frequency)
* Data will only be triggered when **phone** **is** **unlocked**
* Data can only be triggered where there is **network connection**
* Only enabled **Data** **Types** from [the Terra Dashboard](https://dashboard.tryterra.co) will be triggered by background delivery.
* If you are using **CustomPermissions,** please ensure the following permissions are enabled for Background Delivery to work correctly:
  * For **Daily: CustomPermissions.STEPS**
  * For **Sleep: CustomPermissions.SLEEP\_ANALYSIS**
  * For **Body: CustomPermissions.BMI, CustomPermissions.HEART\_RATE**
  * For **Activity: CustomPermissions.WORKOUT\_TYPE**
  * For **Nutrition: CustomPermissions.NUTRITION\_CALORIES**
    {% endhint %}
    {% endtab %}

{% tab title="Android (Health Connect & Samsung)" %}
No AppDelegate step is needed. Passing `true` as the third argument (`schedulerOn`) to `initConnection` enables background delivery.

On Health Connect connections, Terra requests Health Connect's background-read permission during the connection flow and schedules the periodic sync as soon as the user grants it.

{% code title="main.dart" lineNumbers="true" %}

```dart
await TerraFlutter.initConnection(
  Connection.healthConnect,
  token,
  true,   // schedulerOn: enables background delivery on Android
  [],     // customPermissions: empty defaults to all
);
```

{% endcode %}

{% hint style="info" %}
`terra_flutter_bridge` 0.10.1 bundles `terra-android` 1.7.2, which schedules the periodic sync even when the background-read permission has not been granted, so it can run without being able to read. A release bundling 1.7.3 or later gates it on the grant.

The Flutter bridge does not currently expose a method to prompt for that permission again, so a user who declines it would need to grant it in the Health Connect app settings.
{% endhint %}
{% endtab %}
{% endtabs %}

## Optional: Filter by source app on iOS

Apple Health aggregates data from every health app on the user's device. If a user has both a cloud-based Terra connection (e.g. WHOOP, Garmin) and the same provider's companion app syncing into Apple Health, you'll receive duplicate data: once from the cloud API and once from the Apple Health SDK.

Use `setIgnoredSources` to tell the SDK to skip data from specific apps in HealthKit. Call this **once on every app launch**, after `TerraFlutter.initTerra()` completes. It is not persisted across app restarts. On Android, this function is a no-op.

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';

// After TerraFlutter.initTerra() completes:
await TerraFlutter.setIgnoredSources(["com.whoop.app", "com.garmin.connect.mobile"]);
```

Common bundle identifiers:

| App            | Bundle identifier           |
| -------------- | --------------------------- |
| WHOOP          | `com.whoop.app`             |
| Garmin Connect | `com.garmin.connect.mobile` |
| Fitbit         | `com.fitbit.FitbitMobile`   |
| Oura           | `com.ouraring.oura`         |

{% hint style="info" %}
To find a specific app's bundle identifier, have the user check **Settings → Health → Data Access & Devices** on their iPhone.
{% endhint %}

From here, health data events reach your data destination, such as a webhook, automatically.

You can also request historical data to backfill, to verify that data exists, or as a fallback.

Check out the [Flutter SDK reference](https://docs.tryterra.co/reference/mobile-sdks/flutter) for details about all the functions in the SDK.

## Disconnect a user

In order to disconnect an SDK user, you may use the [same endpoint as for Web API-based integrations](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser), called from your **backend**.

## Read data on demand

To fetch data for a date range from the device, call `getDaily`. With `toWebhook` set to `false`, the data comes back in the response.

{% code title="pollDaily.dart" lineNumbers="true" %}

```dart
import 'package:terra_flutter_bridge/terra_flutter_bridge.dart';
import 'package:terra_flutter_bridge/models/enums.dart';
import 'package:terra_flutter_bridge/models/responses.dart';

Future<void> getData() async {
  // Example connection type and dates
  Connection connection = Connection.appleHealth;  // Assuming Connection is an enum with APPLE
  DateTime startDate = DateTime.now().subtract(Duration(days: 1));  // Replace with actual start date
  DateTime endDate = DateTime.now();                                // Replace with actual end date
  
  // Optionally, send data to webhook or not
  bool toWebhook = false;  // Set to false to receive the data in the response

  // Call the getDaily function
  DataMessage? dataMessage = await TerraFlutter.getDaily(connection, startDate, endDate, toWebhook: toWebhook);

  // Handle the response based on the structure of DataMessage
  if (dataMessage?.error != null) {
    throw Exception("Error getting data ${dataMessage?.error}");
  }
  
  // Process data here: `dataMessage?.data`
}
```

{% endcode %}

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [Terra Grip](/mobile-sdks/terra-grip-companion-app): connect mobile sources without an app of your own.
* [Health data events](/unified-api/receiving-data-updates): handle the data the SDK uploads.
* [Historical data requests](/unified-api/requesting-historical-data): backfill from your backend.


# Terra Grip

Connect your users' Apple Health, Health Connect or Samsung Health through Terra Grip when you don't have a mobile app of your own.

Apple Health, Health Connect and Samsung Health keep their data on the phone, so they normally need the [Terra mobile SDK](/mobile-sdks/mobile-only-sources) inside your own app. If you don't have an app, **Terra Grip** can be that app for you.

Send your user to Grip in one of two ways: through the [Terra authentication widget](#connect-a-user-with-the-terra-widget), or with a link you create from your backend. The user opens it on their phone, Grip asks for access to their health data, and Grip then sends that data to Terra in the background. You receive it on your webhook or destination like any other source.

Grip is on the [App Store](https://apps.apple.com/app/id6789555253) and [Google Play](https://play.google.com/store/apps/details?id=co.tryterra.streamingdemo).

| `resource`       | Store                                  | Phone   |
| ---------------- | -------------------------------------- | ------- |
| `APPLE`          | Apple Health                           | iPhone  |
| `HEALTH_CONNECT` | Health Connect                         | Android |
| `SAMSUNG`        | Samsung Health, through Health Connect | Android |

## Connect a user with the Terra widget

If you use the [Terra authentication widget](/unified-api/implementation-terra-widget), add `"sdk_app": "grip"` to the body of `POST https://access.tryterra.co/api/widget/session`:

```json
{
  "reference_id": "user123@email.com",
  "providers": "APPLE,HEALTH_CONNECT,SAMSUNG,GARMIN",
  "sdk_app": "grip",
  "auth_success_redirect_url": "https://myapp.com/success",
  "auth_failure_redirect_url": "https://myapp.com/failure"
}
```

When the user picks Apple Health, Health Connect or Samsung Health on their phone, the widget shows a **Connect** button that opens Grip, or the store listing if Grip isn't installed. The user then connects in Grip as in [The user connects](#the-user-connects). Other providers in the same session keep their normal login.

* An unknown `sdk_app` value returns a `400`.
* `apple_app_url` and `samsung_app_url` take precedence over `sdk_app`.

## Connect a user with a link

{% stepper %}
{% step %}

### Create a link

From your **backend**, call [`/auth/authenticateUser`](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-authenticateuser) with `sdk_app` set to `"grip"`. Make one call per user, with your own ID for that user as `reference_id`.

{% code title="Command Line" %}

```bash
curl --request POST --url 'https://api.tryterra.co/v2/auth/authenticateUser?resource=APPLE' \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
      "sdk_app": "grip",
      "reference_id": "user_123",
      "auth_success_redirect_url": "https://example.com/connected",
      "auth_failure_redirect_url": "https://example.com/failed"
  }'
```

{% endcode %}

The `auth_url` in the response is a Grip link:

```
https://grip.tryterra.co/health-auth?token=…&dev_id=…&reference_id=…&auth_success_redirect_url=…&auth_failure_redirect_url=…&resource=APPLE
```

{% endstep %}

{% step %}

### Send the link to the user

Show the link to the user **on their phone**, for example behind a "Connect Apple Health" button on your web page. Each link is for one user.

A link expires 3 minutes after you create it and works once, so create it when the user is ready to connect.
{% endstep %}

{% step %}

### The user connects

On the right phone, the link opens Grip, or the store listing if Grip isn't installed.

1. Grip opens on its **Health** tab and shows which kinds of data you will receive.
2. The user taps **Agree**, and the phone's own permission sheet asks for access.
3. Grip sends the **last 7 days** of data to Terra, then opens your success URL.
   {% endstep %}

{% step %}

### Handle the redirect

Grip opens your `auth_success_redirect_url` only after the user has agreed, granted access, and the first sync has finished. It adds `user_id`, `reference_id` and `resource` to the URL.

Use absolute `https` URLs for both redirects. If something goes wrong, Grip opens your `auth_failure_redirect_url` with a `reason`:

| `reason`            | When                                                         |
| ------------------- | ------------------------------------------------------------ |
| `ios_only`          | An `APPLE` link was opened on Android                        |
| `android_only`      | A `HEALTH_CONNECT` or `SAMSUNG` link was opened on an iPhone |
| `outside_of_mobile` | The link was opened on a computer                            |
| Any other text      | Connecting failed, for example the link had expired          |
| {% endstep %}       |                                                              |
| {% endstepper %}    |                                                              |

## Receive data

Syncing is **automatic and runs in the background**. There is no sync button, and the user doesn't need to open Grip for new data to reach you.

* **Background delivery**: iOS wakes Grip when Apple Health receives new data, so a workout reaches Terra without the user opening the app.
* **Scheduled uploads**: Terra's own background scheduler also posts what the SDK already holds.
* **When the user opens Grip**: Grip syncs again, at most once every 15 minutes.

### Which data you receive

Grip asks only for the data types enabled for your developer ID in the [Terra Dashboard](https://dashboard.tryterra.co/), out of activity, daily, sleep, body, nutrition and menstruation. Enable a type later and existing users must open a new link to grant it.

### Backfill

Apple Health data lives on the phone, so a backfill you request from the dashboard is carried out by Grip the next time the user opens Grip's **Health** tab.

### Several customers on one phone

One phone can share with several Terra customers. A new link adds a customer rather than replacing one, and each customer receives only the data types its own account enables. Grip lists every connected customer on its Health tab.

## Limits

* **The legacy `/auth/generateWidgetSession` ignores `sdk_app`.** Use the [widget session endpoint](#connect-a-user-with-the-terra-widget) or `/auth/authenticateUser`.
* **The phone can't end a customer's connection.** Grip's **Forget** only hides a customer from its list, and sharing continues. A connection ends when you [deauthenticate the user](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser), or when the user turns off Terra Grip's Apple Health access in iOS **Settings**. The second stops every customer on that phone at once.

## Health Connect and Samsung Health on Android

The same flow works on Android with `resource=HEALTH_CONNECT` or `resource=SAMSUNG`. A few differences:

* Grip never reads menstruation data on Android.
* Health Connect shows a second sheet with **Access past data** and **Access data in the background**. Both start off. Without them Grip still connects, but syncs reach back only 30 days and run only while Grip is open.
* `SAMSUNG` reads Samsung Health through Health Connect. Grip sees data only after the user turns on Health Connect sync in Samsung Health (**Settings > Health Connect**).
* One customer connected through both stores is two separate connections.
* The user's off switch is turning off Terra Grip's access in Health Connect settings.

## Next steps

* [Health data events](/unified-api/receiving-data-updates): handle the data Grip sends to your destination.
* [Terra authentication widget](/unified-api/implementation-terra-widget): add Grip to an existing widget session.


# Planned workouts on Apple Watch

Put the plans you create with the Planned Workouts API on an Apple Health user's Apple Watch through the iOS or React Native SDK.

Plans you create with the [Planned Workouts API](/planned-workouts-api/overview) for an Apple Health user appear on that person's Apple Watch, in the Workout app, on the day they are planned for.

* `schedulingStatus`: returns whether the SDK can put plans on this person's Watch. It never shows a prompt.
* `requestScheduling`: shows WorkoutKit's permission sheet, once, so the SDK can put plans on the Watch.
* `planned`: returns the person's planned workouts.
* `markComplete`: reports a planned workout as done.

Planned workouts must first be created using [Terra's REST API](/planned-workouts-api/overview) on your backend. Once the person allows scheduling, every SDK sync run reads what changed and updates the Watch. There is no sync call to make.

## Before you begin

* The [iOS SDK](/mobile-sdks/ios-sdk-2) or the [React Native SDK](/mobile-sdks/react-native-sdk-2), connected with `connect(.health, ...)` (Swift) or `connect('health', ...)` (React Native).
* iOS 17 or later on the iPhone, and an Apple Watch paired with it. On anything else, `schedulingStatus()` returns `unsupported` and nothing is put on a Watch.
* No extra entitlement or background mode. Scheduling runs inside the SDK's existing sync runs.
* iOS only. On Android, `terra.plannedWorkouts` is `undefined`.

## Ask for scheduling permission

Putting plans on the Watch needs one permission, which WorkoutKit asks for with its own system sheet. Ask from a screen where it makes sense to the person, such as your training plan screen. The SDK never shows the sheet on its own.

{% tabs %}
{% tab title="Swift" %}
{% code title="TrainingPlanView\.swift" lineNumbers="true" %}

```swift
import TerraSDK

func enablePlannedWorkouts(connection: Connection) async {
    let plans = connection.workouts

    if await plans.schedulingStatus() == .notDetermined {
        await plans.requestScheduling()
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="React Native" %}
{% code title="TrainingPlanScreen.tsx" lineNumbers="true" %}

```typescript
import { terra } from './terra';

const enablePlannedWorkouts = async () => {
  const plans = terra.plannedWorkouts; // undefined on Android

  if (plans && (await plans.schedulingStatus()) === 'notDetermined') {
    await plans.requestScheduling();
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

`schedulingStatus()` returns one of:

| Status          | Meaning                                                                |
| --------------- | ---------------------------------------------------------------------- |
| `unsupported`   | Below iOS 17, or the device cannot schedule workouts. Hide the feature |
| `notDetermined` | Not asked yet. Call `requestScheduling()`                              |
| `denied`        | The person refused. Only the Settings app changes this                 |
| `authorized`    | Plans go on the Watch on every sync run                                |

When the person allows it, the SDK puts their plans on the Watch straight away.

## Create plans on your backend

Create and change plans with the [Planned Workouts API](/planned-workouts-api/overview), for the Terra user the SDK connected. You don't call anything else in the app.

| In Terra          | On the Watch                                                                                                       |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| A plan is created | Scheduled at 09:00 local time on its day. A plan for today created after 09:00 is scheduled a few minutes from now |
| A plan is changed | The workout is replaced, or moved to its new day                                                                   |
| A plan is deleted | The workout is removed                                                                                             |

Workouts your app schedules itself with WorkoutKit are left alone, and reported to Terra so your backend can see them.

### When the Watch is updated

Scheduling runs at the end of each sync run, so plans reach the Watch when the SDK next runs:

* **Scheduling allowed**: straight after `requestScheduling()` is allowed.
* **Permission grant or new link**: after a `permissions.request` that first asks for a category with an upload route, or a `connect` that makes a new link.
* **Foreground**: when the app becomes active, at most once every 15 minutes.
* **Background**: on the SDK's background refresh task.

A HealthKit background delivery wake uploads the new health data only. It does not update the Watch.

### Plans that cannot be scheduled

{% hint style="warning" %}
A plan WorkoutKit cannot represent is refused, and Terra is told why:

| Reason                 | Cause                                                                                        |
| ---------------------- | -------------------------------------------------------------------------------------------- |
| `activity_unsupported` | WorkoutKit cannot build a custom workout for this activity                                   |
| `goal_unsupported`     | A step's goal is one WorkoutKit refuses for this activity and location                       |
| `malformed`            | The workout has a goal, unit or step the SDK does not recognise, or no interval block to run |
| `no_workout`           | The plan has no workout to schedule                                                          |
| `past`                 | The plan's day has already passed on the device                                              |
| `completed`            | The plan is already done                                                                     |

Any copy of a refused plan already on the Watch is removed. When the Watch's schedule is full, the remaining plans stay queued and are scheduled as earlier sessions pass.
{% endhint %}

## Check what happened

Each run reports on [`diagnostics.events()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#diagnostics.events):

* `plannedWorkoutsScheduled`, with how many plans were scheduled, removed and refused.
* `plannedWorkoutScheduleFailed`, with a failure code, when the run could not read the queue or reach WorkoutKit.

## Read plans in the app

You can also read the person's plans and report progress from the app:

{% tabs %}
{% tab title="Swift" %}
{% code lineNumbers="true" %}

```swift
let upcoming = try await plans.planned()
try await plans.markComplete(id: upcoming[0].id)
```

{% endcode %}
{% endtab %}

{% tab title="React Native" %}
{% code lineNumbers="true" %}

```typescript
const upcoming = await plans.planned();
await plans.markComplete(upcoming[0].id);
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [Android SDK](/mobile-sdks/android-sdk-2): connect Health Connect and Samsung Health.
* [React Native SDK](/mobile-sdks/react-native-sdk-2): use planned workouts from React Native.


# Samsung Health

Read Samsung Health data with the Android SDK, through Health Connect or directly with the Samsung add-on.

There are two ways to get Samsung Health data into Terra with the [Android SDK](/mobile-sdks/android-sdk-2). This page compares them and shows how to set up each one.

* **Through Health Connect.** Samsung Health writes most of its data into Health Connect, and the core SDK reads it as `Source.HEALTH`. Nothing extra to install.
* **Directly.** The [`terra-android-samsung`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#samsung-health-add-on) add-on reads Samsung Health's own store as [`Source.SAMSUNG_HEALTH`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#source), through Samsung's Health Data SDK.

## Choose a route

|                         | Through Health Connect                                                            | Directly (add-on)                                                                        |
| ----------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Setup                   | Core SDK only                                                                     | Add-on, plus Samsung's SDK that you download, plus Samsung partner approval for your app |
| Devices                 | Any Android phone with Health Connect                                             | Phones with Samsung Health, Android 10 (API 29) or later                                 |
| Other apps' data        | Yes, everything in Health Connect                                                 | No, only what Samsung Health recorded itself                                             |
| Samsung Health workouts | Only the ones Samsung Health copies into Health Connect, which is not all of them | All of them                                                                              |
| Time to ship            | Now                                                                               | After Samsung approves your app                                                          |

Start with Health Connect. It covers most Samsung users with no extra approval. Add the direct route when you need every Samsung Health workout, or Samsung data Health Connect does not carry.

## Read through Health Connect

Follow the [Android SDK](/mobile-sdks/android-sdk-2) guide and connect `Source.HEALTH`. Samsung Health's data arrives with everything else in Health Connect.

The person has to allow Samsung Health to share its data with Health Connect, in Samsung Health's settings.

## Read directly with the add-on

### Register your app with Samsung

Every app that reads Samsung Health directly must be registered with Samsung under its own package name. Samsung approves each package separately, so Terra's registration does not cover your app.

1. Submit a partner request to Samsung with your app's **package name** and the **SHA-256 fingerprint** of its signing certificate. If your app is already approved for Samsung's older Samsung Health SDK for Android, that approval does not carry over. Submit Samsung's migration partner request from your existing Samsung developer account. See Samsung's [migration guide](https://developer.samsung.com/health/data/migration-guide/overview.html).
2. Until Samsung approves it, reads only work with Samsung Health's **developer mode** turned on: in Samsung Health, open **Settings > About Samsung Health** and tap the version number repeatedly. Developer mode is for testing only. Your users will not have it.

### Download Samsung's SDK

1. Sign in at [Samsung Health Data SDK](https://developer.samsung.com/health/data/overview.html) and download **version 1.1.0**. It is the only version the add-on supports.
2. Unpack it and copy `samsung-health-data-api.aar` into your app module's `libs/` folder.

### Add the dependencies

{% code title="app/build.gradle.kts" %}

```kotlin
plugins {
    id("kotlin-parcelize")
}

dependencies {
    implementation("co.tryterra:terra-android:2.2.1")
    implementation("co.tryterra:terra-android-samsung:2.2.1")

    // Samsung's SDK, which your app packages
    implementation(files("libs/samsung-health-data-api.aar"))
    // Samsung's SDK needs both at runtime and does not bring them
    implementation("com.google.code.gson:gson:2.11.0")
    implementation("org.jetbrains.kotlin:kotlin-parcelize-runtime:<your Kotlin version>")
}
```

{% endcode %}

### Register the store

Register the Samsung store when you build `Terra`:

{% code title="YourApp.kt" %}

```kotlin
import co.tryterra.sdk.health.samsung.samsungHealth

terra = Terra(
    this,
    devId = BuildConfig.TERRA_DEV_ID,
    tokenProvider = { yourBackend.mintTerraToken() },
) {
    samsungHealth()
}
BackgroundSync.register(this, terra)
```

{% endcode %}

### Connect and request permissions

Samsung Health has its own permission sheet, so it has its own launcher. Reach it through [`terra.on(Source.SAMSUNG_HEALTH)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.on):

{% code title="ConnectActivity.kt" %}

```kotlin
// in onCreate
samsungLauncher = terra.on(Source.SAMSUNG_HEALTH).permissions.launcher(this)

// on tap
terra.connect(Source.SAMSUNG_HEALTH, EndUser.Reference(signedInUser.id))
terra.on(Source.SAMSUNG_HEALTH).permissions.request(
    read = setOf(DataCategory.DAILY, DataCategory.SLEEP, DataCategory.ACTIVITY),
    launcher = samsungLauncher,
)
```

{% endcode %}

From here it behaves like Health Connect: the same triggers, the same two-year first sync, and the same background runs. The token provider is called for the Samsung link the same way.

The Samsung store reads only. It does not write to Samsung Health.

## Use both routes

An app can connect `Source.HEALTH` and `Source.SAMSUNG_HEALTH` on the same phone.

* **The Samsung store uploads only what Samsung Health recorded itself.** Data Samsung Health imported from other apps is left to Health Connect.
* **The Health Connect store uploads everything else.** The Samsung store takes precedence by default, and Health Connect fills in the gaps.

The SDK checks every record type on every read. If the Samsung store can no longer send a record type, for example because the user withdrew access, disconnected, or uninstalled Samsung Health, the SDK automatically falls back to Health Connect. Record types the Samsung store does not read as records, such as resting heart rate, HRV, respiratory rate, steps, energy, distance and floors, always stay with Health Connect.

{% hint style="warning" %}
**Day totals are not de-duplicated.** Health Connect cannot leave one app out of its daily totals, so its daily steps, energy, distance and floors include Samsung Health's. Samsung's daily totals are the whole device's figure too. A user connected through both may show the same steps in both daily totals, each under its own source. Individual records are never sent twice.
{% endhint %}

If you want the SDK to send readings from both Health Connect and the Samsung store, including the records they share, register the store with `samsungHealth(dedupeHealthConnect = false)`.

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}

## Next steps

* [React Native SDK](/mobile-sdks/react-native-sdk-2): connect Apple Health and Health Connect from one codebase.
* [Health data events](/unified-api/receiving-data-updates): handle the data the SDK uploads.


# iOS upgrade guide

Move an iOS app from TerraiOS 1.x to 2.x: the package and import change, Info.plist and entitlements, reference IDs, and old calls mapped to new ones.

`TerraiOS` 2.x is a rebuild, not an update. The package URL stays the same, but the module, the entry point and every call changed. Plan it as a migration.

## Update the package and the import

{% tabs %}
{% tab title="Swift Package Manager" %}
Change the version rule on `https://github.com/tryterra/TerraiOS` to `from: "2.0.0"` (any 2.x release). Link the `TerraSDK` product.
{% endtab %}

{% tab title="CocoaPods" %}
Change the version requirement to `pod 'TerraiOS', '~> 2.x'` (any 2.x release).
{% endtab %}
{% endtabs %}

Change every import:

{% code title="YourApp.swift" %}

```swift
// 1.x
import TerraiOS

// 2.x
import TerraSDK
```

{% endcode %}

## Update Info.plist and entitlements

|                                           | 1.x                                        | 2.x                       |
| ----------------------------------------- | ------------------------------------------ | ------------------------- |
| `BGTaskSchedulerPermittedIdentifiers`     | `co.tryterra.data.post.request`            | `co.tryterra.sdk.refresh` |
| Background modes                          | Background fetch and Background processing | Background fetch          |
| HealthKit background delivery entitlement | Required                                   | Required                  |
| `NSHealthUpdateUsageDescription`          | Required                                   | Required                  |

The minimum iOS version is now 15.

## Move `reference_id` to your backend

In 1.x the app passed `referenceId` to `Terra.instance`. In 2.x your backend sets it when it mints the token. Use the same value 1.x used, so existing users keep their `user_id`:

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

The app still names the person, on every `connect`: [`connect(.health, for: .reference(user.id))`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.connect), with the same value your backend puts in the token. The SDK restores a stored link only for the person it was made for. When someone else signs in on the same phone, it retires the old link and links again, so their data does not arrive under the previous person's `reference_id`. If your backend sends no `reference_id`, pass [`.anonymous`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#enduser). Terra still trusts only the reference inside the token.

## Map the calls

| 1.x                                                                          | 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Terra.instance(devId:referenceId:requestPermissions:completion:)`           | [`Terra(devID:tokenProvider:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.init). Synchronous, no completion handler. Build it once, at launch                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `initConnection(type: .APPLE_HEALTH, token:customReadTypes:schedulerOn:)`    | [`try await terra.connect(.health, for: .reference(user.id))`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.connect), then [`try await terra.permissions.request(read:write:workouts:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#permissions.request)                                                                                                                                                                                                                                                                                                                                                     |
| `token:` argument on `initConnection`                                        | The `tokenProvider` closure on `Terra(...)`, called only when a new link is needed. Or `connect(.health, for: .reference(user.id), using: token)` for a token already in hand                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `customReadTypes: Set<CustomPermissions>`                                    | [`read: [DataCategory]`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#datacategory), for example `[.daily, .sleep, .activity, .body]`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `requestHealthKitPermissions()`                                              | `terra.permissions.request(...)`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `requestPermissions: false`                                                  | Not needed. `Terra(...)` and `connect` never present a sheet. Only `permissions.request` does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `referenceId:` argument on `Terra.instance`                                  | `reference_id` on your backend's token request, and the [`EndUser`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#enduser) you pass to every `connect`                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `getUserId(type: .APPLE_HEALTH)`                                             | [`try await terra.connections`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terra.connections), and [`connection.userID`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#connection) on what `connect` returns                                                                                                                                                                                                                                                                                                                                                                                                        |
| `Terra.setUpBackgroundDelivery()`                                            | [`BackgroundSync.register(terra: terra)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#backgroundsync.register). See [Set up background delivery](/mobile-sdks/ios-sdk-2#set-up-background-delivery)                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `schedulerOn:`                                                               | Removed. Background delivery is `BackgroundSync.register`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `getDaily`, `getBody`, `getSleep`, `getActivity`, ... with `toWebhook: true` | Removed from the device. [Historical data requests](/unified-api/requesting-historical-data) from your backend with `to_webhook=true`. The device serves it on its next run                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `getDaily` with `toWebhook: false`                                           | [`terra.daily.steps(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#dailymetrics.steps). In 2.2.0 and later, also [`terra.daily.totals(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#dailymetrics.totals) for each day's distance, active and basal energy, flights climbed and exercise minutes, [`terra.daily.intraday(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#dailymetrics.intraday) for the samples under those totals, and [`terra.body.restingHeartRate(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.restingheartrate) for resting heart rate |
| `getBody` with `toWebhook: false`                                            | [`terra.body.heartRate(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.heartrate). In 2.2.0 and later, also [`terra.body.restingHeartRate(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.restingheartrate) and [`terra.body.readings(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.readings) for weight, height, BMI, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate                                                                                                           |
| `getSleep` with `toWebhook: false`                                           | [`terra.sleep.segments(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#sleepmetrics.segments)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `getActivity` with `toWebhook: false`                                        | [`terra.activity.workouts(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.workouts). In 2.2.0 and later, each `Workout` also carries `title`, and [`terra.activity.routes(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.routes) and [`terra.activity.intensity(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.intensity) return GPS tracks and speed, power and cadence                                                                                                                                                                   |
| `getNutrition` with `toWebhook: false`                                       | 2.2.0 and later: [`terra.nutrition.quantities(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#nutritionmetrics.quantities), one value per nutrient sample, and [`terra.nutrition.hydration(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#nutritionmetrics.hydration) for water. Before 2.2.0 there is no local read: read nutrition from Terra's API or your webhook on your backend                                                                                                                                                                                                                       |
| `getMenstruation` with `toWebhook: false`                                    | 2.2.0 and later: [`terra.menstruation.flow(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#menstruationmetrics.flow) and [`terra.menstruation.events(in:)`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#menstruationmetrics.events). Request `.menstruation` first. Before 2.2.0 there is no local read: read it from Terra's API or your webhook                                                                                                                                                                                                                                                               |
| `getAthlete` with `toWebhook: false`                                         | 2.2.0 and later: [`terra.athlete.profile()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#athletemetrics.profile). Request `.athlete` first. Before 2.2.0 there is no local read: read it from Terra's API or your webhook                                                                                                                                                                                                                                                                                                                                                                                                       |
| `subscribe(forDataTypes:)` with `Terra.updateHandler`                        | [`for await _ in await terra.daily.changes()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#dailymetrics.changes), and the other namespaces' `changes()`. A hint that something changed, not the samples: read them with the local reads above                                                                                                                                                                                                                                                                                                                                                                                   |
| `Terra.checkAuthentication(connection:devId:)`                               | [`await terra.diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#diagnostics.state), which answers `.linkRevoked` when Terra no longer accepts the device's link                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `postActivity`, `postBody`, `postNutrition`                                  | [`terra.activity.log`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#activitymetrics.log), [`terra.body.log`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#bodymetrics.log), [`terra.nutrition.log`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#nutritionmetrics.log). These log samples your app measured itself. Writing Terra's own payloads back into Apple Health is not available                                                                                                                                                                                                                 |
| `setIgnoredSources([...])`                                                   | Not available. The SDK uploads data from every app the person granted access to. Merging it with other connections is up to your backend                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `enablePlannedWorkoutBackendSync`, `syncPlannedWorkoutsFromBackend`          | [`connection.workouts.requestScheduling()`](/mobile-sdks/planned-workouts-apple-watch#ask-for-scheduling-permission), once. After that every sync run puts the person's plans on their Apple Watch. There is no sync call to make. See [Planned workouts on Apple Watch](/mobile-sdks/planned-workouts-apple-watch)                                                                                                                                                                                                                                                                                                                          |
| FreeStyleLibre (`activateSensor`, `readGlucoseData`)                         | Removed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| Disconnect through `deauthenticateUser` on your backend                      | Still works. On the device, [`connection.disconnect()`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#connection.disconnect) also forgets the link and revokes its key                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

Every call is `async` and throws a [`TerraError`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terraerror). Each case has a stable [`code`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terraerror.code) and an [`isRetryable`](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2#terraerror.isretryable) answer.

### Before and after

{% tabs %}
{% tab title="1.x" %}
{% code title="YourApp.swift" %}

```swift
import TerraiOS

Terra.instance(devId: "<DEV_ID>", referenceId: "<USER_ID>") { manager, error in
    guard let manager else { return }
    if manager.getUserId(type: .APPLE_HEALTH) == nil {
        manager.initConnection(type: .APPLE_HEALTH, token: tokenFromBackend,
                               customReadTypes: [], schedulerOn: true) { success, error in }
    }
}

// AppDelegate
Terra.setUpBackgroundDelivery()
```

{% endcode %}
{% endtab %}

{% tab title="2.x" %}
{% code title="YourApp.swift" %}

```swift
import TerraSDK

let terra = Terra(devID: "<DEV_ID>") { try await backend.mintTerraToken() }

// At launch, before the first await
BackgroundSync.register(terra: terra)

// When the user taps "Connect Apple Health"
try await terra.connect(.health, for: .reference(user.id))
try await terra.permissions.request(read: [.daily, .sleep, .activity, .body])
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}


# Android upgrade guide

Move an Android app from terra-android 1.x to 2.x: the coordinate and package changes, the manifest, reference IDs, old calls mapped to new ones, and the Samsung Health setup.

`terra-android` 2.x is a rebuild, not an update. The Maven coordinate stays the same, but the Kotlin package, the entry point and every call changed. Plan it as a migration.

## Update the dependencies and imports

{% code title="app/build.gradle.kts" %}

```kotlin
dependencies {
    implementation("co.tryterra:terra-android:<VERSION>") // latest 2.x on Maven Central
}
```

{% endcode %}

If you used the 1.x Samsung-direct artifact `co.tryterra:android-sdk`, remove it. Samsung direct is now an add-on to `terra-android`: see [Update the Samsung Health setup](#update-the-samsung-health-setup) below.

Change every import from `co.tryterra.terra` to `co.tryterra.sdk`:

{% code title="YourApp.kt" %}

```kotlin
// 1.x
import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

// 2.x
import co.tryterra.sdk.Terra
import co.tryterra.sdk.Source
import co.tryterra.sdk.EndUser
import co.tryterra.sdk.DataCategory
import co.tryterra.sdk.background.BackgroundSync
```

{% endcode %}

## Update the manifest

The 1.x AAR declared Health Connect permissions for you. The 2.x AAR declares none. Declare exactly the permissions for the categories you request, plus `READ_HEALTH_DATA_IN_BACKGROUND` and `READ_HEALTH_DATA_HISTORY` if you want background sync and more than 30 days of history. Also declare `INTERNET` and the Health Connect package query. See [Configure health permissions](/mobile-sdks/android-sdk-2#configure-health-permissions).

Declare the privacy policy screen twice, for below and above Android 14. Without the Android 14 `activity-alias`, every read fails with "Incorrect health permission state".

## Move `reference_id` to your backend

In 1.x the app passed `referenceId` to `Terra.instance`. In 2.x your backend sets it when it mints the token. Use the same value 1.x used, so existing users keep their `user_id`:

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

The app still names the person, on every `connect`: [`terra.connect(Source.HEALTH, EndUser.Reference(user.id))`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connect), with the same value your backend puts in the token. The SDK restores a stored link only for the person it was made for. When someone else signs in on the same phone, it retires the old link and links again, so their data does not arrive under the previous person's `reference_id`. If your backend sends no `reference_id`, pass [`EndUser.Anonymous`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#enduser). Terra still trusts only the reference inside the token.

## Map the calls

| 1.x                                                                                                       | 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Terra.instance(devId, referenceId, context) { manager, error -> }`                                       | [`Terra(context, devId = ..., tokenProvider = { ... })`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.invoke). Synchronous. Build it once, in `Application.onCreate`                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `initConnection(Connections.HEALTH_CONNECT, token, context, customPermissions, schedulerOn, startIntent)` | [`terra.connect(Source.HEALTH, EndUser.Reference(user.id))`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connect), then [`terra.permissions.request(read = ..., launcher = launcher)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.request)                                                                                                                                                                                                                                                                                                                                                                |
| `token` argument on `initConnection`                                                                      | The `tokenProvider` on `Terra(...)`, called only when a new link is needed. Or `terra.connect(Source.HEALTH, EndUser.Reference(user.id), token)` for a token already in hand                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `referenceId` argument on `Terra.instance`                                                                | `reference_id` on your backend's token request, and the [`EndUser`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#enduser) you pass to every `connect`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `customPermissions: Set<CustomPermissions>`                                                               | [`read: Set<DataCategory>`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#datacategory), for example `setOf(DataCategory.DAILY, DataCategory.SLEEP)`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `Connections.HEALTH_CONNECT`, `Connections.GOOGLE_FIT`                                                    | [`Source.HEALTH`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#source)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `Connections.SAMSUNG`                                                                                     | `Source.HEALTH` reads everything in Health Connect, Samsung Health's data included. For Samsung's own store, `Source.SAMSUNG_HEALTH` with the add-on                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `getUserId(type)`                                                                                         | [`terra.connections()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.connections), and `userId` on what `connect` returns                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `checkAuth(...)`                                                                                          | [`terra.diagnostics.state()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#diagnostics.state), which is `LinkRevoked` when Terra no longer accepts the device's link                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `allGivenPermissions(...)`                                                                                | [`terra.permissions.statuses()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.statuses), or [`status(category)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.status) for one                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `schedulerOn = true`, `enableBackgroundDelivery`, `isBackgroundDeliveryAvailable`                         | [`BackgroundSync.register(context, terra)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#backgroundsync.register) in `Application.onCreate`, and [`terra.permissions.backgroundReadStatus()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#permissions.backgroundreadstatus). Background read is asked for on the same sheet as everything else                                                                                                                                                                                                                                                                                |
| `getDaily`, `getBody`, ... with `toWebhook = true`                                                        | Removed from the device. [Historical data requests](/unified-api/requesting-historical-data) from your backend with `to_webhook=true`. The device serves it on its next run                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `getDaily` with `toWebhook = false`                                                                       | [`terra.daily.steps(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.steps). In 2.2.1 and later, also [`terra.daily.totals(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.totals) for each day's distance, active and basal energy and floors, [`terra.daily.intraday(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.intraday) for the records under those totals, and [`terra.body.restingHeartRate(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.restingheartrate) for resting heart rate, which needs `DAILY` |
| `getBody` with `toWebhook = false`                                                                        | [`terra.body.heartRate(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.heartrate). In 2.2.1 and later, also [`terra.body.readings(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#bodymetrics.readings) for weight, height, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate                                                                                                                                                                                                                                                      |
| `getSleep` with `toWebhook = false`                                                                       | [`terra.sleep.segments(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#sleepmetrics.segments)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `getActivity` with `toWebhook = false`                                                                    | [`terra.activity.workouts(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.workouts). In 2.2.1 and later, each `Workout` also carries `title`, and [`terra.activity.routes(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.routes) and [`terra.activity.intensity(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#activitymetrics.intensity) return GPS tracks and speed, power and cadence                                                                                                                                                                   |
| `getNutrition` with `toWebhook = false`                                                                   | 2.2.1 and later: [`terra.nutrition.quantities(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#nutritionmetrics.quantities), one value per nutrient a meal recorded, and [`terra.nutrition.hydration(range)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#nutritionmetrics.hydration) for water. Before 2.2.1 there is no local read: read nutrition from Terra's API or your webhook on your backend                                                                                                                                                                                                                    |
| `subscribe(...)` with `Terra.updateHandler`                                                               | [`terra.daily.changes()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#dailymetrics.changes) and the other namespaces' `changes()`, which return a `Flow` of hints. Read the samples with the local reads                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `isHealthConnectAvailable(context)`                                                                       | 2.2.1 and later: [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.availability), which needs no connection and returns `StoreAvailability.Available` or the reason, such as `ProviderAppMissing` or `ProviderAppTooOld`. Before 2.2.1 there is no separate call: `connect` and `permissions.request` throw [`TerraError.HealthDataUnavailable`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terraerror) when Health Connect is missing or needs an update                                                                                                                                          |
| `openHealthConnect(context)`                                                                              | No equivalent                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Disconnect through `deauthenticateUser` on your backend                                                   | Still works. On the device, [`terra.disconnect(Source.HEALTH)`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terra.disconnect) also forgets the link and revokes its key                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |

Every call is a `suspend` function and throws a [`TerraError`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#terraerror). Each case has a stable `code` and an `isRetryable` answer.

### Before and after

{% tabs %}
{% tab title="1.x" %}
{% code title="YourApp.kt" %}

```kotlin
import co.tryterra.terra.Terra
import co.tryterra.terra.enums.Connections

Terra.instance("<DEV_ID>", "<USER_ID>", this) { manager, error ->
    if (manager.getUserId(Connections.HEALTH_CONNECT) == null) {
        manager.initConnection(
            connection = Connections.HEALTH_CONNECT,
            token = tokenFromBackend,
            context = this,
            customPermissions = setOf(),
            schedulerOn = true,
            startIntent = null,
        ) { success, error -> }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="2.x" %}
{% code title="YourApp.kt" %}

```kotlin
import co.tryterra.sdk.DataCategory
import co.tryterra.sdk.EndUser
import co.tryterra.sdk.Source
import co.tryterra.sdk.Terra
import co.tryterra.sdk.background.BackgroundSync

// Application.onCreate
terra = Terra(this, devId = "<DEV_ID>", tokenProvider = { backend.mintTerraToken() })
BackgroundSync.register(this, terra)

// Activity.onCreate, before anything suspends
launcher = terra.permissions.launcher(this)

// On tap
terra.connect(Source.HEALTH, EndUser.Reference(user.id))
terra.permissions.request(
    read = setOf(DataCategory.DAILY, DataCategory.SLEEP, DataCategory.ACTIVITY),
    launcher = launcher,
)
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Update the Samsung Health setup

In 1.x, Samsung Health came two ways: `Connections.SAMSUNG` in `terra-android`, which read Samsung Health's data out of Health Connect, and the separate `co.tryterra:android-sdk` artifact, which read Samsung's store directly.

In 2.x:

* **Through Health Connect**, connect `Source.HEALTH`. There is no Samsung-only filter: Health Connect's data from every app is uploaded.
* **Directly**, add `co.tryterra:terra-android-samsung` (the same version as `terra-android`) and register it with [`samsungHealth()`](https://docs.tryterra.co/reference/mobile-sdks/android-sdk-2#samsunghealth).

Two things change for the direct route:

* **You download Samsung's SDK yourself.** Samsung's licence forbids redistributing its Health Data SDK. You download version 1.1.0 from Samsung and package it in your app.
* **Your app needs its own Samsung approval.** Samsung approves each package name and signing certificate separately. Register yours with Samsung, and use Samsung Health's developer mode until it is approved.

See [Samsung Health](/mobile-sdks/samsung-health) for the setup, and for how the two stores avoid sending a record twice.

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}


# React Native upgrade guide

Move a React Native app from terra-react 1.x to the 2.x wrapper: the package change, old calls mapped to new ones, and the behaviour that changed.

The 2.x React Native wrapper is a rebuild of `terra-react`, not an update. It runs the native [iOS SDK 2.x](/mobile-sdks/ios-sdk-2) and [Android SDK 2.x](/mobile-sdks/android-sdk-2) underneath, so it has their behaviour: automatic background sync, a token provider instead of a token argument, and a `connect` that names the end user. Every call changed. Plan it as a migration.

## Replace the package

Remove `terra-react`, including a Samsung-tagged `terra-react` build, and install the 2.x wrapper, `@tryterra/react-native`:

```bash
npm uninstall terra-react
npm install @tryterra/react-native
cd ios && pod install
```

The wrapper needs React Native 0.81 or later, with the New Architecture. It pulls in the native SDKs itself: the `TerraiOS` pod on iOS and `co.tryterra:terra-android` on Android.

Change every import:

{% code title="App.tsx" %}

```typescript
// 1.x
import { initTerra, initConnection, Connections } from 'terra-react';

// 2.x
import { createTerra, EndUser, TerraError } from '@tryterra/react-native';
```

{% endcode %}

## Set up the native side

The wrapper builds its native client when the app launches, before any JavaScript runs, because background delivery needs it then. Your dev ID therefore lives in native configuration, not in JavaScript.

### iOS

1. Update Info.plist and entitlements as the native guide describes: [Update Info.plist and entitlements](https://docs.tryterra.co/mobile-sdks/pages/pxWMVghOXRxsGOo0WgzI#update-info.plist-and-entitlements). The background task identifier is now `co.tryterra.sdk.refresh`, not `co.tryterra.data.post.request`.
2. Add your dev ID to Info.plist under the `TerraDevID` key.
3. Remove the 1.x `Terra.setUpBackgroundDelivery()` call from your `AppDelegate`, and call the wrapper's bootstrap first thing in `application(_:didFinishLaunchingWithOptions:)`:

{% code title="AppDelegate.swift" %}

```swift
import TerraReactNative

func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
    TerraReactNative.bootstrap()
    // ...the rest of your launch code
    return true
}
```

{% endcode %}

### Android

1. Set `minSdkVersion` to 28 and `compileSdkVersion` to 36.
2. Update the manifest as the native guide describes: [Update the manifest](/mobile-sdks/android-migrating-to-2#update-the-manifest). The 2.x SDK declares no Health Connect permission for you.
3. Add your dev ID inside `<application>`:

{% code title="AndroidManifest.xml" %}

```xml
<meta-data android:name="co.tryterra.sdk.DEV_ID" android:value="<YOUR_DEV_ID>" />
```

{% endcode %}

Nothing else is needed in code: the wrapper sets itself up before `Application.onCreate`. If your app removed WorkManager's default initializer to configure WorkManager itself, call `TerraReactNative.bootstrap(this)` at the end of `Application.onCreate`.

Without the native setup, every call rejects with `bridge.not_bootstrapped`, and the error's `details.line` names what to add.

## Move `reference_id` to your backend

In 1.x the app passed `referenceId` to `initTerra`. In 2.x your backend sets it when it mints the token. Use the same value 1.x used, so existing users keep their `user_id`:

{% code title="Your backend" %}

```bash
curl --request POST \
  --url 'https://api.tryterra.co/v2/auth/generateAuthToken?reference_id=<YOUR_USER_ID>' \
  --header 'dev-id: <YOUR_DEV_ID>' \
  --header 'x-api-key: <YOUR_API_KEY>'
```

{% endcode %}

The app still names the person, on every connect, with an `EndUser`:

```typescript
EndUser.reference(user.id) // the same value your backend puts in the token
EndUser.anonymous          // only if your backend sends no reference_id
```

The native SDK restores a stored link only for the person it was made for. When someone else signs in on the same phone, it retires the old link and links again, so their data does not arrive under the previous person's `reference_id`. The end user never reaches Terra as identity: Terra trusts only the reference inside the token. See [Name the end user](/mobile-sdks/ios-sdk-2#name-the-end-user).

## Supply tokens from JavaScript

In 1.x you passed a token to every `initConnection`. In 2.x the native SDK asks for a token only when it has to link: the first time, after a reinstall, for a different end user, or when Terra stopped accepting the device's key. A normal launch restores the link without one.

Create the client once, at module scope, with a token provider that asks your backend:

{% code title="terra.ts" %}

```typescript
import { createTerra } from '@tryterra/react-native';

export const terra = createTerra({
  tokenProvider: () => api.terraToken(), // a fresh token minted by your backend
});
```

{% endcode %}

| Option           | Description                                                                                                                                                                          |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tokenProvider`  | Returns a promise of a one-time token. Called only while `connect` makes a new link and was given no token. A restored link and a background run never call it                       |
| `tokenTimeoutMs` | How long the native side waits for `tokenProvider`. Defaults to 30 seconds. After that the connect rejects with `bridge.token_timeout` on iOS and `token_provider_failed` on Android |

A token you already hold, for example from a QR code or a deep link, goes straight into the connect: `terra.connect('health', endUser, { token })`. A token passed this way always creates a fresh link.

## Map the calls

| 1.x                                                                          | 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `initTerra(devID, referenceId)`                                              | `createTerra({ tokenProvider })`, once at module scope. The dev ID moves to native configuration ([Set up the native side](#set-up-the-native-side)) and `referenceId` to your backend and the `EndUser` ([Move `reference_id` to your backend](#move-reference_id-to-your-backend)). `terra.attach()` reports the native client: `{ bootstrapped, devId, platform, sdkVersion, backgroundRegistered }`                                                                                                                                                                                                                                                                                              |
| `initConnection(connection, token, schedulerOn, customPermissions)`          | `terra.connect('health', EndUser.reference(user.id))`, then `terra.permissions.request({ read, write, workouts })`. `connect` never shows a permission sheet. Only `permissions.request` does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `token` argument on `initConnection`                                         | The `tokenProvider` from [Supply tokens from JavaScript](#supply-tokens-from-javascript). Or `terra.connect('health', endUser, { token })` for a token already in hand                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `Connections.APPLE_HEALTH`, `Connections.HEALTH_CONNECT`                     | `'health'`: Apple Health on iOS, Health Connect on Android                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `Connections.SAMSUNG`, or a Samsung-tagged `terra-react`                     | `'health'` reads Samsung Health's data through Health Connect. `'samsungHealth'` reads Samsung Health directly, on Android only. See [Update the Samsung Health setup](#update-the-samsung-health-setup)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `customPermissions: CustomPermissions[]`                                     | `read` in `permissions.request`, from `'activity'`, `'body'`, `'daily'`, `'sleep'` and `'nutrition'`. In 2.2.1 and later, also `'menstruation'`, and `'athlete'` on iOS                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `schedulerOn`                                                                | Removed. Background sync is registered natively when the app starts. `terra.background.isRegistered()` answers whether it was                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `checkAuth(connection, devID)`                                               | `terra.diagnostics.state()`, which is `{ state: 'linkRevoked' }` when Terra no longer accepts the device's link                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `getUserId(connection)`                                                      | `terra.connections()`, and `userId` on each connection. `connect` also resolves with the `Connection`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `getDaily`, `getBody`, `getSleep`, `getActivity`, ... with `toWebhook: true` | Removed from the device. [Historical data requests](/unified-api/requesting-historical-data) from your backend with `to_webhook=true`. The device serves it on its next run                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `getDaily` with `toWebhook: false`                                           | [`terra.daily.steps`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.steps), which takes a range, for example `terra.daily.steps({ kind: 'lastDays', days: 7 })`. In 2.2.1 and later, also [`terra.daily.totals`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.totals) for each day's distance, energy, floors and, on iOS, exercise minutes, [`terra.daily.intraday`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#daily.intraday) for the records under those totals, and [`terra.body.restingHeartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.restingheartrate) for resting heart rate |
| `getBody` with `toWebhook: false`                                            | [`terra.body.heartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.heartrate). In 2.2.1 and later, also [`terra.body.restingHeartRate`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.restingheartrate) and [`terra.body.readings`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#body.readings) for weight, height, body fat, lean mass, HRV, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate                                                                                                                                                                                 |
| `getSleep` with `toWebhook: false`                                           | [`terra.sleep.segments`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#sleep.segments)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `getActivity` with `toWebhook: false`                                        | [`terra.activity.workouts`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.workouts). In 2.2.1 and later, each `Workout` also carries `title`, and [`terra.activity.routes`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.routes) and [`terra.activity.intensity`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#activity.intensity) return GPS tracks and speed, power and cadence                                                                                                                                                                                                                                    |
| `getNutrition` with `toWebhook: false`                                       | 2.2.1 and later: [`terra.nutrition.quantities`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#nutrition.quantities), one value per nutrient, and [`terra.nutrition.hydration`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#nutrition.hydration) for water. Before 2.2.1 there is no local read: read nutrition from Terra's API or your webhook on your backend                                                                                                                                                                                                                                                                                            |
| `getMenstruation` with `toWebhook: false`                                    | 2.2.1 and later: [`terra.menstruation.flow`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#menstruation.flow) and [`terra.menstruation.events`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#menstruation.events). Request `'menstruation'` first. Before 2.2.1 there is no local read: read it from Terra's API or your webhook                                                                                                                                                                                                                                                                                                                            |
| `getAthlete` with `toWebhook: false`                                         | 2.2.1 and later, iOS only: [`terra.athlete?.profile()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#athlete.profile). Request `'athlete'` first. `terra.athlete` is `undefined` on Android. Before 2.2.1 there is no local read: read it from Terra's API or your webhook                                                                                                                                                                                                                                                                                                                                                                                                      |
| `postActivity(Connections.APPLE_HEALTH, payload)`                            | `terra.activity.log(entries)`, on iOS and Android. `terra.body.log`, `terra.body.logHeartRate`, `terra.daily.log`, `terra.sleep.log` and `terra.nutrition.log` write the other kinds. Each resolves with the new record IDs, and the namespace's `delete(id)` removes one                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `isHealthConnectAvailable()`                                                 | 2.2.1 and later: [`terra.availability()`](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2#availability), which needs no connection and resolves with `{ kind: 'available' }` or the reason, such as `{ kind: 'providerAppMissing' }`. Before 2.2.1 there is no separate call: `connect` and `permissions.request` reject with `health_data_unavailable` when Health Connect is missing or needs an update                                                                                                                                                                                                                                                                          |
| `openHealthConnect()`                                                        | No equivalent in 2.x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `grantedPermissions()`                                                       | `terra.permissions.statuses()` on Android, one `PermissionStatus` per category. `terra.permissions.status(category)` for one category on both platforms                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `setIgnoredSources([...])`                                                   | Not available. The SDK uploads data from every app the person granted access to. Merging it with other connections is up to your backend                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Disconnect through `deauthenticateUser` on your backend                      | Still works. On the device, `terra.disconnect('health')` also forgets the link and revokes its key                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

### Errors

1.x resolved with `{ success, error }`. In 2.x a failed call rejects with a `TerraError`. `TerraError.from(error)` turns anything caught into one:

| Property    | Description                                                                                      |
| ----------- | ------------------------------------------------------------------------------------------------ |
| `code`      | A stable code, for example `token_rejected`, `health_data_unavailable` or `bridge.token_timeout` |
| `retryable` | Whether the same call could succeed if repeated                                                  |
| `message`   | A readable description                                                                           |
| `source`    | The source the error is about, when there is one                                                 |
| `details`   | Extra fields for some codes, such as `line` on `bridge.not_bootstrapped`                         |

### Before and after

{% tabs %}
{% tab title="1.x" %}
{% code title="App.tsx" %}

```typescript
import { Connections, initConnection, initTerra } from 'terra-react';

await initTerra(devID, user.id);
const result = await initConnection(
  Connections.APPLE_HEALTH,
  tokenFromBackend,
  true, // schedulerOn
  [],   // customPermissions
);
if (!result.success) {
  console.error(result.error);
}
```

{% endcode %}
{% endtab %}

{% tab title="2.x" %}
{% code title="App.tsx" %}

```typescript
import { EndUser, TerraError } from '@tryterra/react-native';
import { terra } from './terra'; // the client from terra.ts above

try {
  const connection = await terra.connect('health', EndUser.reference(user.id));
  console.log('Terra user_id', connection.userId);

  await terra.permissions.request({
    read: ['daily', 'sleep', 'activity', 'body'],
  });
} catch (error) {
  const terraError = TerraError.from(error);
  console.error(terraError.code, terraError.message);
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Update the Samsung Health setup

In 1.x, Samsung Health came two ways: `Connections.SAMSUNG`, which read Samsung Health's data out of Health Connect, and a Samsung-tagged `terra-react` build, which read Samsung's store directly.

In the 2.x wrapper:

* **Through Health Connect**, connect `'health'`. Samsung Health's data in Health Connect is uploaded with every other app's.
* **Directly**, on Android only, connect `'samsungHealth'`. It needs Samsung's partner approval and Samsung's own `samsung-health-data-api.aar`, which you download from Samsung and add to your app module. Then set `terraSamsungHealth=true` in `android/gradle.properties`. Without that property, `'samsungHealth'` rejects with `health_data_unavailable`. See [Samsung Health](/mobile-sdks/samsung-health) for approval and what the direct connection reads.

Calls that take a source default to `'health'`. Pass `'samsungHealth'` to reach Samsung Health instead, for example `terra.permissions.request({ read: ['daily'] }, 'samsungHealth')` or `terra.diagnostics.state('samsungHealth')`. Reads, writes and change streams always go to Health Connect.

## Request permissions

`write: ['activity']` asks for workouts and everything a workout can carry: energy and distance. To ask for less, leave `'activity'` out of `write` and pass `workouts` scopes, such as `{ activity: { kind: 'running' }, energy: true, distance: true }`. The [iOS](/mobile-sdks/ios-sdk-2#request-permissions) and [Android](/mobile-sdks/android-sdk-2#write-permissions-and-workout-scopes) guides cover the details, including why `permissions.writeStatus('activity')` can be `denied` while a run still logs.

On Android, `permissions.request` resolves with what the sheet granted, `{ read, write, workouts }`, narrowed to what this call asked for. Check it instead of assuming the person said yes. On iOS it resolves with `undefined`, because HealthKit does not tell an app whether a read was allowed.

When the request asks to read anything, the Android sheet also asks for background read and history read, if your manifest declares them. Check them afterwards with `terra.permissions.backgroundReadStatus()` and `terra.permissions.historyReadStatus()`. Both are Android only, and `undefined` on iOS.

The wrapper registers the Android permission sheet with each of your activities as it is created, so there is no launcher to set up. Two Android-only rejections are new in the wrapper. Both are retryable:

| Code                                  | Cause                                                                                           |
| ------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `bridge.no_activity`                  | No activity is on screen to present the sheet, for example because the app is in the background |
| `bridge.permission_sheet_unavailable` | A sheet from an earlier request is still up, or the activity's sheet was released               |

## Behaviour that changed

* **Sync is automatic.** The SDK uploads after a permission request grants something new, after a new link, when the app comes to the foreground, and on background runs. There is no call that starts a sync.
* **The first sync reaches two years back**, then only what changed. See the [iOS](/mobile-sdks/ios-sdk-2) and [Android](/mobile-sdks/android-sdk-2) guides for what syncs and when.
* **A link is restored without a network call.** `terra.connect('health', endUser)` for the same end user on a normal launch costs nothing and works offline.
* **Diagnostics.** `terra.diagnostics.state()`, `terra.diagnostics.lastDelivery()` and `terra.diagnostics.events(listener)` replace guessing from `checkAuth`. `terra.diagnostics.report()` returns a redacted support report that never contains a health value.

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}


# iOS SDK 1.x

Connect Apple Health users with the TerraiOS 1.x SDK: install it, initialise it, connect a user and enable background delivery.

This page shows how to integrate Apple Health in your iOS app with `TerraiOS` 1.x. It covers SDK initialization, user connection, permission handling and background data updates.

{% hint style="info" %}
`TerraiOS` 1.x is no longer the current version. For new apps, use the [iOS SDK](/mobile-sdks/ios-sdk-2) (2.x). To move an existing app, follow [iOS upgrade guide](/mobile-sdks/ios-migrating-to-2).
{% endhint %}

The `TerraiOS` SDK supports the following integrations:

* Apple Health

## Install the SDK

{% @supademo/embed url="<https://app.supademo.com/demo/cm23anelu2a4c13b3fg1gd9pu>" demoId="cm23anelu2a4c13b3fg1gd9pu" %}

1. Add `https://github.com/tryterra/TerraiOS` as a package dependency to your Xcode project.
2. Add these capabilities:
   1. Healthkit > Healthkit Background Delivery
   2. Background Modes > Background processing
   3. Background modes > Background fetch
3. In your `Info.plist`, add the following:

<table><thead><tr><th width="348.9085693359375">Key</th><th width="371.258056640625">Value</th></tr></thead><tbody><tr><td>Privacy - Health Share Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Privacy - Health Records Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Privacy - Health Update Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Permitted background task scheduler</td><td><code>co.tryterra.data.post.request</code></td></tr></tbody></table>

## Initialize the SDK

The first step is to initialize the Terra SDK. This is done by creating a `TerraManager` instance which allows you to interact with the Terra SDK.

The initialization only needs to be done once on app start (for example in your `ContentView.swift` or an equivalent file), and ideally whenever the app is brought into the foreground. This ensures that the SDK is properly set up and ready to be used.

### Import TerraiOS

In your Xcode project, you should now be able to import Terra SDK

{% code title="ContentView\.swift" lineNumbers="true" %}

```swift
import TerraiOS
```

{% endcode %}

### Get a `TerraManager` instance

In order to interact with the SDK, you need a **`TerraManager`** instance.

Call `Terra.instance()` with the following arguments:

* `devId`: Your **Developer ID** provided by Terra.
* `referenceId`: An **ID of your choice** to identify your app user.
* `requestPermissions` **(optional, defaults to `true`)**: Whether to automatically trigger the HealthKit permission popup when an existing Apple Health user is reconnected on launch. Set to `false` if you want returning users to be recognized silently and want the popup to be deferred to an explicit user action. See [Control when the HealthKit popup appears](#control-when-the-healthkit-popup-appears) below.
* `completion` : Callback with a `TerraManager` or an instance `TerraError`

Find more details in the SDK Reference: [Terra manager initialization function](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#terra.instance)

{% code title="ContentView\.swift" lineNumbers="true" %}

```swift
import TerraiOS

var terra: TerraManager?

Terra.instance(devId: "<YOUR_DEV_ID>", referenceId: "<REFERENCE_ID>") { manager, error in
    guard let manager = manager, error == nil else {
        fatalError("🤯: \(error?.localizedDescription ?? "unknown error")")
    }

    // TerraManager instance to access the SDK functions
    terra = manager
}
```

{% endcode %}

The `TerraManager` instance is thereafter ready to be used to call SDK functions!

This call is asynchronous. Make sure it completes before you use the manager.

## Connect an Apple Health user

Once you’ve initialized the SDK, you can connect the Apple Health user. This is done by calling the [`initConnection()`](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#initconnection) method provided by the `TerraManager` instance that you created above.

### Call `initConnection()`

This method triggers the **Apple Health permission popup** and establishes the connection.

From `TerraManager`, call [`initConnection()`](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#initconnection) with the following arguments:

* `type`: Specify the connection type as `.APPLE_HEALTH` to connect the Apple Health account.
* `token`: A **one-time authentication token** generated from your **backend** server using the /auth/generateAuthToken endpoint. This ensures secure communication between your app and the Terra servers.
* `customReadTypes`: A **set of permissions** that define what data you want to request from Apple Health (e.g., heart rate, steps). If empty, it defaults to all available permissions. See [Permissions mapping](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping) for every value and the Apple Health type it requests.
* `schedulerOn`: This parameter has no effect. Background delivery is controlled by calling `Terra.setUpBackgroundDelivery()` in your AppDelegate. See [Enable background delivery](#enable-background-delivery) below.

To learn more about these parameters and their different options, check the [iOS SDK Reference.](https://docs.tryterra.co/reference/mobile-sdks/ios-swift)

{% code title="UserConnectionManager.swift" lineNumbers="true" %}

```swift
// Prepare the arguments
let token = "<AUTH_TOKEN>" // replace with the token generated from your backend with Terra
let customPermissions: Set<CustomPermissions> = [] // customize permissions if needed
let schedulerOn = true // no effect on iOS, see setUpBackgroundDelivery() below

// Start a connection to Apple Health
terra.initConnection(
    type: .APPLE_HEALTH,
    token: token,
    customReadTypes: customPermissions,
    schedulerOn: schedulerOn
) { success, error in
    guard success, error == nil else {
        fatalError("🤯: \(error?.localizedDescription ?? "unknown error")")
    }
    // Connection successful. The Apple Health permission popup was shown
}
```

{% endcode %}

After a successful call of `initConnection()` with a valid token, an Apple Permission screen will pop up!

{% hint style="info" %}
**The permission popup shows once.** Apple Health only shows the permission popup once, so calling `initConnection()` multiple times won’t trigger the popup again unless:

* you call `initConnection` with an expanded set of `customPermissions`
* the app is deleted and reinstalled.
  {% endhint %}

{% hint style="info" %}
**WebView apps.**

* Apple HealthKit implements the permissions popup as a WebView.
* If your app is also based on a WebView, you will need to interrupt your WebView, call `initConnection`, then upon completion re-open your WebView.
  {% endhint %}

#### Generate an auth token

To be able to call the `initConnection()` method, you need to pass a `token` as an argument.

This `token` is a **single-use token** created to ensure the authentication endpoint for creating a connection (and connecting the SDK to Terra's servers) does not get abused.

Generate the token with this endpoint <mark style="color:orange;">`POST`</mark>`https://api.tryterra.co/v2/auth/generateAuthToken` . Make sure to call it with your Terra `x-api-key` and `dev-id` in the headers from **your backend server.** After you generate the token, provide the response to your client side using your own logic.

{% code title="CLI" %}

```bash
curl --request POST \
  --url https://api.tryterra.co/v2/auth/generateAuthToken \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>'
```

{% endcode %}

For every parameter, see the [`/auth/generateAuthToken` endpoint](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-generateauthtoken) in the API reference.

{% hint style="warning" %}

* During the development phase, it it acceptable to place this call on the **client** side, exposing your API key in your mobile app.
* For a production implementation, **DO NOT** expose your API key this way, and make sure to **only** make this call from your **backend.**
  {% endhint %}

## Control when the HealthKit popup appears

By default, the HealthKit permission popup is triggered in two situations:

1. When your app calls [`initConnection()`](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#initconnection) to establish a new connection.
2. When `Terra.instance(...)` reconnects a returning Apple Health user **and** iOS has no stored authorization for your app (for example: the app was reinstalled and iOS cleared the authorization, or the user revoked permissions in Settings).

For most apps this is the desired behavior. However, some apps want the popup to appear **only** in response to an explicit user action, for example the user tapping "Connect Apple Health" inside your app UI. Two common reasons:

* **Multi-device:** the same user opens your app on a second device (e.g. an iPad) where they have not yet opted into HealthKit. You don't want the popup to appear on that device until they actively choose to connect.
* **Reinstall:** the user previously granted HealthKit in a prior install, deleted the app, and reinstalled. You don't want the popup to appear the moment they relaunch; you want it gated on their explicit action.

### Defer the popup

Pass `requestPermissions: false` to `Terra.instance(...)` so that returning users are recognized silently without triggering the popup. Then call `requestHealthKitPermissions(...)` when the user explicitly opts in.

{% code title="DeferredPrompt.swift" lineNumbers="true" %}

```swift
// On app launch, recognize the returning user silently; no popup.
Terra.instance(devId: "<DEV_ID>", referenceId: "<REFERENCE_ID>", requestPermissions: false) { manager, error in
    guard let manager = manager, error == nil else { return }
    self.terra = manager
    // `manager` is ready. If this referenceId already had an Apple Health connection,
    // it's reconnected silently. No HealthKit popup has been shown.
}

// Later, when the user taps "Connect Apple Health" in your UI:
func userTappedConnectAppleHealth() {
    terra?.requestHealthKitPermissions { success, error in
        // If iOS hasn't already determined permissions for this install, the popup
        // is shown here. If it has (e.g. the user previously granted and the install
        // hasn't changed), the call returns synchronously with success.
    }
}
```

{% endcode %}

{% hint style="info" %}
`requestPermissions: false` only materially changes behavior when `Terra.instance` finds an existing Apple Health connection for this device + `referenceId` that needs re-authorization. For a first-time user, a new device, or a reinstall where the device identifier changed, `Terra.instance` does not auto-prompt regardless of the flag. The popup is only ever triggered by your `initConnection()` or `requestHealthKitPermissions()` call.
{% endhint %}

## Cross-device and reinstall behavior

If the same user (same `referenceId`) connects Apple Health from multiple devices, or reconnects after a reinstall that reset the device's vendor identifier, **each device produces a distinct Terra `user_id`**. The Terra backend keys Apple Health connections on the tuple `(deviceId, devId, referenceId)`: if the device identifier changes, a new connection is created.

### Scenario matrix

| Scenario                                                                                                                         | HealthKit popup on launch?                                                                                                                                                                            | Resulting Terra `user_id`                          | What you should do                                                                                                                                                                                                           |
| -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Returning user, same device and `referenceId` (vendor ID unchanged)                                                              | Only if iOS cleared authorization, for example the user revoked permissions in Settings, or a reinstall where the vendor ID persisted because another app from your App Store team is still installed | Same as before                                     | Nothing: `Terra.instance` handles it. If you want to suppress that edge-case popup on launch, see [Control when the HealthKit popup appears](#control-when-the-healthkit-popup-appears) and use `requestPermissions: false`. |
| Same device, different `referenceId` (e.g. user logout/login on the same device)                                                 | No                                                                                                                                                                                                    | A **new** `user_id` when you call `initConnection` | Call `initConnection` when the new user opts in                                                                                                                                                                              |
| Different device (e.g. iPhone → iPad), same `referenceId`                                                                        | No                                                                                                                                                                                                    | A **new** `user_id` when you call `initConnection` | Dedupe webhooks on `reference_id`, or gate `initConnection` to a single primary device per user                                                                                                                              |
| Reinstall where the vendor ID changed (the common case: the user deleted every app from your App Store team before reinstalling) | No                                                                                                                                                                                                    | A **new** `user_id` when you call `initConnection` | Treat as a new connection; dedupe on `reference_id`                                                                                                                                                                          |

{% hint style="info" %}
Apple generates a new `identifierForVendor` for your app only when the user deletes **every** app from your App Store team from the device and then reinstalls one. If your team only ships one app, a reinstall almost always resets the vendor ID, producing a new Terra `user_id`. If your team ships multiple apps that users tend to keep installed, the vendor ID often persists across reinstalls of any one of them.
{% endhint %}

### Webhook payload example

This means data from the same real person can arrive at your webhook under **different `user_id`s** sharing the **same `reference_id`**:

```json
// From iPhone connection
{ "user": { "user_id": "<uid-A>", "reference_id": "user-42" }, ... }

// From iPad connection (same person, same reference_id)
{ "user": { "user_id": "<uid-B>", "reference_id": "user-42" }, ... }
```

### Handle several connections for one person

* Deduplicate data on your side by grouping webhook events on `reference_id`.
* Terra does not automatically link Apple Health connections that share a `reference_id` but differ on device identifier. This is a deliberate design decision because HealthKit data is device-local and may legitimately differ per device.
* If you only want one device to be the data source, gate your `initConnection()` call on your own app's "primary device" logic and do not call it on other devices for the same user.

## Validate the connection

To ensure a connection is still valid on the client side, make sure to use the [`getUserid()`](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#getuserid) from `TerraManager` every time you reinitialize the SDK. This function is synchronous and returns a `user_id` right away if a user is connected or nil if none exists.

{% hint style="info" %}
**Always validate the connection before using the SDK**

Check if a `user_id` exists right after **initializing the Terra SDK** to see if the connection still exists.

1. **Check if the User is Connected**
   1. If the function returns a user ID, the user is still connected, 🎉 keep vibing along!
   2. If the function returns <mark style="color:red;">`nil`</mark>, the user needs to reconnect.
2. **Re-connect if Needed**\
   If the connection is lost, you can call `terra.initConnection()` again to re-establish the connection.

Calling `terra.initConnection()` when the user is already connected or just needs a reconnection will re-establish the connection if necessary, and the user flow will remain uninterrupted.

On Apple Health, note that a `user_id` only tells you the connection exists on our side, not that your app still holds HealthKit access. Deleting an app clears its HealthKit authorization while the Terra connection survives, so the permission screen can still appear on the next `initConnection()` if iOS has not yet determined permissions for the current install.
{% endhint %}

## Enable background delivery

1. Go to your **AppDelegate**'s `didFinishLaunchingWithOptions` function.
2. Add [`Terra.setUpBackgroundDelivery()`](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#setupbackgrounddelivery)

This will ensure you get updates for the user's Apple Health data automatically sent to your destination.

{% code title="AppDelegate.swift" lineNumbers="true" %}

```swift
import UIKit
import TerraiOS

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
      _ application: UIApplication, 
      didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        Terra.setUpBackgroundDelivery()
        return true
    }
}
```

{% endcode %}

{% hint style="success" %}

## iOS Background Delivery Behaviour:

* Data will still be triggered if the **app** **is** **killed** (with much lower frequency)
* Data will only be triggered when **phone** **is** **unlocked**
* Data can only be triggered where there is **network connection**
* Only enabled **Data** **Types** from [the Terra Dashboard](https://dashboard.tryterra.co) will be triggered by background delivery.
* If you are using **CustomPermissions,** please ensure the following permissions are enabled for Background Delivery to work correctly:
  * For **Daily: CustomPermissions.STEPS**
  * For **Sleep: CustomPermissions.SLEEP\_ANALYSIS**
  * For **Body: CustomPermissions.BMI, CustomPermissions.HEART\_RATE**
  * For **Activity: CustomPermissions.WORKOUT\_TYPE**
  * For **Nutrition: CustomPermissions.NUTRITION\_CALORIES**
    {% endhint %}

## Optional: Filter by source app

Apple Health aggregates data from every health app on the user's device. If a user has both a cloud-based Terra connection (e.g. WHOOP, Garmin) and the same provider's companion app syncing into Apple Health, you'll receive duplicate data: once from the cloud API and once from the Apple Health SDK.

Use `setIgnoredSources` to tell the SDK to skip data from specific apps in HealthKit. Call this **once on every app launch**, after `Terra.instance()` completes. It is not persisted across app restarts.

```swift
// After Terra.instance() completes:
Terra.setIgnoredSources(["com.whoop.app", "com.garmin.connect.mobile"])
```

Common bundle identifiers:

| App            | Bundle identifier           |
| -------------- | --------------------------- |
| WHOOP          | `com.whoop.app`             |
| Garmin Connect | `com.garmin.connect.mobile` |
| Fitbit         | `com.fitbit.FitbitMobile`   |
| Oura           | `com.ouraring.oura`         |

{% hint style="info" %}
To find a specific app's bundle identifier, have the user check **Settings → Health → Data Access & Devices** on their iPhone.
{% endhint %}

You now receive health data events automatically at your destination (for example, a webhook).

You can also request historical data to backfill, to verify that data exists, or as a fallback.

Check out the [iOS SDK reference](https://docs.tryterra.co/reference/mobile-sdks/ios-swift) for details about all the functions in the SDK.

## Example app

1. Go to the main entry point of your app, and initialize the TerraiOS SDK.

{% code title="ContentView\.swift" lineNumbers="true" %}

```swift
import SwiftUI
import TerraiOS

// Main entry point for the app
struct ContentView: View {
    
    @State private var terra: TerraManager?

    // Function to initialise the Terra SDK once here for the whole project (async)
    private func initializeTerraSDK(_ completion: @escaping () -> Void) {
        Terra.instance(devId: "YOUR_DEV_ID", referenceId: "<YOUR REFERENCE ID>") { manager, error in
            guard let manager = manager, error == nil  else {
                fatalError("Error initialising Terra SDK: \(error?.localizedDescription)")
            }
            terra = manager   // TerraManager initialised!
            completion() 
        }
    }

    // Function to ensure the user is connected to Apple Health or restablish it.
    private func ensureUserConnection() {
        guard let terra = terra else { return }
        connectUser(terra, "AUTH TOKEN") {
            // User connection ensured!
            // Continue here if more processing needed...
        }
    }

    var body: some View {
        Text("Welcome to my App!")
            .onAppear {
                // initialise SDK and ensure user is connected
                initializeTerraSDK(ensureUserConnection)
            }
    }
}
```

{% endcode %}

2. Define the core functions of the SDK that you need to use, e.g. `getUserId()`, `initConnection()`

{% code title="UserConnectionManager.swift" lineNumbers="true" %}

```swift
import TerraiOS

// connect the user to Apple Health
func connectUser(_ terra: TerraManager, _ token: String, _ completion: @escaping () -> Void) {
    // getUserId is synchronous and tells you whether a Terra connection already exists for
    // this device, so you only spend a one-time auth token when there isn't one. It is not
    // a HealthKit permission check. See the warning below.
    guard terra.getUserId(type: .APPLE_HEALTH) == nil else {
        // Already registered with us. Make sure HealthKit access is in place for this
        // install: iOS presents the sheet only for types it has not yet determined, so this
        // is a no-op when the user has already been asked.
        terra.requestHealthKitPermissions { _, _ in
            completion()
        }
        return
    }

    // register the connection and trigger the permission screen (asynchronous)
    terra.initConnection(type: .APPLE_HEALTH, token: token) {success, error in
        guard success && error == nil else {
            print("🤯: \(error?.localizedDescription ?? "unknown error")")
            return
        }
        // Apple Health user connected!
        completion()
    }
}
```

{% endcode %}

{% hint style="warning" %}
`getUserId(type: .APPLE_HEALTH)` tells you whether a Terra connection is registered for this device. It never consults HealthKit, so it is not a permission check. Deleting your app clears the HealthKit authorization on the device but leaves the Terra connection in place, so on reinstall `getUserId` can still return a value. This happens when the device's vendor ID and your `referenceId` are both unchanged (see [Cross-device and reinstall behavior](#cross-device-and-reinstall-behavior)).

Use it to decide whether you need to register a new connection, never to decide whether to ask for HealthKit access. If your app reads a non-`nil` `user_id` as "permissions are fine" and the sheet was never completed on that install (for example you passed `requestPermissions: false`, or the user dismissed it), the connection stays registered with us while every HealthKit read comes back empty, and the payloads we deliver contain no readings. iOS does not report read grants back to your app, so there is no flag that separates "denied" from "no data" after the fact.
{% endhint %}

## Disconnect a user

In order to disconnect an Apple Health user, you may use [the same endpoint as for Web API-based integrations](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser), called from your **backend**.

## Request historical data

You can request for historical data using one of the [data retrieval functions](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#data-retrieval). You may set `toWebhook` to false if you wish for the callback function to return the data payload on the client side.

{% code title="Swift" lineNumbers="true" %}

```swift
terra.getDaily(type: .APPLE_HEALTH, startDate: startDate, endDate: endDate, toWebhook: false) {
    success, payload, err in
    guard success, err == nil else {
        fatalError("🤯: \(err?.localizedDescription ?? "unknown error")")
    }
    // Data is stored in `payload`
    print(payload)
}
```

{% endcode %}

The getter functions are asynchronous, so include a callback as in the example above.

## Write data

* [postActivity](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#postactivity): allows you to write a completed activity to a user's Apple Health
* [postNutrition](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#postnutrition): allows you to write a nutrition log to a user's Apple Health
* [postBody](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#postbody): allows you to write a body measurement to a user's Apple Health

{% tabs %}
{% tab title="postActivity" %}
In order to write a completed activity to a user's Apple Health, use the [postActivity](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#postactivity) function as below.

{% hint style="warning" %}
`device_data` must be passed in for postActivity to succeed. Requires iOS 14+.
{% endhint %}

{% code title="Swift" lineNumbers="true" %}

```swift
import TerraiOS

func postActivityData(terra: TerraManager) {
    let activityData = TerraActivityData(
        heart_rate_data: TerraHeartRateData(
            summary: TerraHeartRateSummaryData(avg_hr_bpm: 140.0, max_hr_bpm: 180.0)
        ),
        metadata: TerraActivityMetaData(
            type: TerraActivityType.RUNNING.rawValue,
            end_time: Date().terraString,
            start_time: Date().addingTimeInterval(-3600).terraString,
            name: "Morning Run"
        ),
        device_data: TerraDeviceData(name: "Terra"),
        distance_data: TerraActivityDistanceData(
            summary: TerraDistanceSummaryData(distance_meters: 5000.0)
        ),
        calories_data: TerraCaloriesData(total_burned_calories: 600.0)
    )

    terra.postActivity(type: .APPLE_HEALTH, payload: activityData) { success, error in
        guard success, error == nil else {
            print("Error: \(error?.localizedDescription ?? "unknown")")
            return
        }
        print("Activity posted successfully!")
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="postBody" %}
In order to write body measurement data to a user's Apple Health, use the [postBody](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#postbody) function as below.

{% code title="Swift" lineNumbers="true" %}

```swift
import TerraiOS

func postBodyData(terra: TerraManager) {
    let bodyData = TerraBodyData(
        metadata: TerraBodyMetaData(
            start_time: Date().terraString,
            end_time: Date().terraString
        ),
        oxygen_data: TerraOxygenData(avg_saturation_percentage: 98.0),
        glucose_data: TerraGlucoseData(day_avg_blood_glucose_mg_per_dL: 90.0),
        heart_data: TerraBodyHeartData(
            heart_rate_data: TerraHeartRateData(summary: TerraHeartRateSummaryData(
                avg_hr_bpm: 70, resting_hr_bpm: 60
            ))
        ),
        hydration_data: TerraHydrationData(day_total_water_consumption_ml: 2500),
        measurements_data: TerraMeasurementData(measurements: [
            MeasurementDataSample(weight_kg: 70.0)
        ])
    )

    terra.postBody(type: .APPLE_HEALTH, payload: bodyData) { success in
        guard success else {
            print("Error posting body data")
            return
        }
        print("Body data posted successfully!")
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="postNutrition" %}
In order to write nutrition data to a user's Apple Health, use the [postNutrition](https://docs.tryterra.co/reference/mobile-sdks/ios-swift#postnutrition) function as below.

{% code title="Swift" lineNumbers="true" %}

```swift
import TerraiOS

func postNutritionData(terra: TerraManager) {
    let meal = TerraMealData(
        quantity: TerraQuantityModel(unit: 0, amount: 1.0),
        name: "Breakfast Cereal",
        macros: TerraMacrosModel(protein_g: 30.0, carbohydrates_g: 50.0, fat_g: 15.0, calories: 450.0),
        micros: TerraMicrosModel(vitamin_C_mg: 60.0, iron_mg: 8.0)
    )

    let nutritionData = TerraNutritionData(
        meals: [meal],
        summary: TerraNutritonSummary(
            macros: TerraMacrosModel(protein_g: 100.0, carbohydrates_g: 300.0, fat_g: 50.0, calories: 2500.0),
            water_ml: 2000.0
        )
    )

    terra.postNutrition(type: .APPLE_HEALTH, payload: nutritionData) { success in
        guard success else {
            print("Error posting nutrition data")
            return
        }
        print("Nutrition data posted successfully!")
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## Sync planned workouts

* `enablePlannedWorkoutBackendSync`: enables or disables automatic syncing of planned workouts from Terra's backend to Apple Watch via WorkoutKit.
* `syncPlannedWorkoutsFromBackend`: manually triggers a sync of all pending planned workout actions.
* `isPlannedWorkoutBackendSyncEnabled`: returns whether automatic planned workout syncing is currently enabled.

Planned workouts must first be created using [Terra's Planned Workouts API](/planned-workouts-api/overview) on your backend. Once created, the iOS SDK automatically fetches and syncs them to Apple Watch via WorkoutKit.

To automatically sync planned workouts from Terra to Apple Watch, call `enablePlannedWorkoutBackendSync` after successfully connecting Apple Health.

```swift
import TerraiOS
import Foundation

func enablePlannedWorkoutSync(terra: TerraManager) {
    guard #available(iOS 17, *) else {
        print("Planned workouts require iOS 17 or later.")
        return
    }

    terra.enablePlannedWorkoutBackendSync(enabled: true)
    print("Planned workout sync enabled!")
}

func syncPlannedWorkouts(terra: TerraManager) {
    guard #available(iOS 17, *) else {
        print("Planned workouts require iOS 17 or later.")
        return
    }

    terra.syncPlannedWorkoutsFromBackend(type: .APPLE_HEALTH)
}

func observePlannedWorkoutSync() {
    NotificationCenter.default.addObserver(
        forName: .terraPlannedWorkoutSynced,
        object: nil,
        queue: .main
    ) { notification in
        guard #available(iOS 17, *),
              let event = notification.object as? WorkoutSyncEvent else {
            return
        }

        print("Synced workout: \(event.displayName ?? "Workout")")
        print("Action: \(event.actionType)")
    }

    NotificationCenter.default.addObserver(
        forName: .terraPlannedWorkoutSyncCompleted,
        object: nil,
        queue: .main
    ) { notification in
        guard #available(iOS 17, *),
              let result = notification.object as? PlannedWorkoutSyncResult else {
            return
        }

        print("Sync complete.")
        print("Successfully synced: \(result.syncedCount)")
        print("Failed: \(result.failedCount)")
    }
}
```

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}


# Android SDK 1.x

Connect Samsung Health and Health Connect users with the terra-android 1.x SDK: install it, initialise it, connect a user and enable background delivery.

This page shows how to integrate Android health stores in your Android app with `terra-android` 1.x. It covers SDK initialization, user connection, permission handling and background data updates.

{% hint style="info" %}
`terra-android` 1.x is no longer the current version. For new apps, use the [Android SDK](/mobile-sdks/android-sdk-2) (2.x). To move an existing app, follow [Android upgrade guide](/mobile-sdks/android-migrating-to-2).
{% endhint %}

The TerraAndroid SDK supports the following integrations:

* Samsung Health
* Health Connect

## Install the SDK

### Add Terra to `build.gradle`

* Inside the dependencies section of your `build.gradle` file, add the following line of code.

<pre class="language-gradle" data-title="build.gradle"><code class="lang-gradle"><strong>implementation 'co.tryterra:terra-android:{VERSION_NUMBER}'
</strong></code></pre>

* You can find the latest version number on [Maven Central](https://central.sonatype.com/artifact/co.tryterra/terra-android/).

### Sync your project with `build.gradle`

Sync your project with Gradle by clicking the **Sync Project with Gradle Files** button in the toolbar. This will download the TerraAndroid SDK and make it available to your project.

{% hint style="info" %}
**Requirements**

* Your app build config must be for **Android 28 (minSDK 28)** and above.
* The device must have the required app installed, e.g. Health Connect or Samsung Health
  {% endhint %}

### Configure health permissions

{% tabs %}
{% tab title="Apply to use Samsung Health" %}
Terra has a privileged partnership with Samsung that gives you direct access to the Samsung Health SDK, with no Health Connect intermediary. This is the recommended route for Samsung devices.

**1. Apply for Samsung Health access**

Submit your application through the [Samsung Health partnership portal](https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c).

{% hint style="info" %}
While waiting for approval, you can start development immediately using the **Health Connect** route (see the other tab). Switching to Samsung direct later only changes the dependency you pull. No code changes are needed.
{% endhint %}

**2. Install the Samsung-direct SDK**

After approval, replace `co.tryterra:terra-android` with the separate Samsung-direct artifact:

```gradle
implementation 'co.tryterra:android-sdk:{VERSION_NUMBER}'
```

Find the latest version on [Maven Central](https://central.sonatype.com/artifact/co.tryterra/android-sdk). Note that this is a separate artifact, not a tagged version of `terra-android`. Your `initConnection(Connections.SAMSUNG, ...)` call and the rest of your code stay exactly the same.

**3. Add ProGuard rule (required for release builds)**

Add this to your `proguard-rules.pro`:

```proguard
-keep class com.samsung.android.** { *; }
```

Without this, R8 minification will strip Samsung SDK classes and cause runtime crashes in production.

**4. Requirements**

* **Samsung Health** app must be installed on the device
* **Android 28 (minSDK 28)** and above
* Enable **Developer Mode** in Samsung Health on test devices (Settings > About Samsung Health > tap version number repeatedly)
* No additional manifest or Gradle changes are needed: the Terra SDK handles everything
  {% endtab %}

{% tab title="Apply to use Health Connect" %}
**1. In the Health Connect app**

Give all permissions between the apps you wish to read from (e.g. **Samsung Health, Google Fit, etc**) & Health Connect.

**2. Add Health Connect capability to your app**

Include the permission tags under the Activity you wish to link the user to when they click the **privacy policy** link in the Health Connect permission screen. Here are the steps:

1. Go to your Android App's `AndroidManifest.xml`
2. Go to your privacy policy `<activity>` and include the following tags under this `<activity>` tag.

"Your Android manifest needs to have an Activity that displays your app's **privacy policy**, which is your app's rationale of the requested permissions, describing how the user's data is used and handled." (Health Connect)

<pre class="language-xml" data-title="AndroidManifest.xml" data-line-numbers><code class="lang-xml"><strong>&#x3C;intent-filter>
</strong>  &#x3C;action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
 &#x3C;/intent-filter>
  
&#x3C;intent-filter>
   &#x3C;action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
  &#x3C;category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
&#x3C;/intent-filter>
</code></pre>

{% hint style="warning" %}
**Apply for Health Connect access**

Before going live (release), you will need to apply for permissions to access the Health Connect API with Google.

1. Use this [application form](https://developer.android.com/health-and-fitness/guides/health-connect/publish/declare-access#explain-use-data-types).
2. For each permission which you are not using, please add the following lines to your AndroidManifest.xml

```xml
<uses-permission android:name="android.permission.health.READ_HEART_RATE" tools:node="remove"/>
```

with `android.permission.health.XXX` for each permission you aren't using
{% endhint %}
{% endtab %}
{% endtabs %}

## Initialize the SDK

The initialization only needs to be done once on app start (for example in your `MainActivity` file or equivalent), and every time the app is brought into the foreground. This ensures that the SDK is properly set up and ready to be used.

{% hint style="warning" %}
The SDK should be initialized every time your app is started.

This is a necessary prerequisite for other SDK functions to run as expected
{% endhint %}

### Import `Terra` and `TerraManager`

In your Android Studio project, you should now be able to import classes from the Terra SDK.

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
```

{% endcode %}

### Get a `TerraManager` instance

To do this, run the [Terra manager initialization function](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#instance) as below:

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Terra.instance("YOUR DEV ID", "REFERENCE ID", this) { manager, error ->
            error?.let {
                throw IllegalStateException("🤯: Error initialising terra ${it.message}")
            }
            terra = manager
        }
    }
}
```

{% endcode %}

This call is asynchronous. Make sure it completes before you use the manager.

## Connect a user

Once Terra is initialized, you can create a connection (e.g. Samsung Health or Health Connect).

Call [`terra.initConnection`](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#initconnection) from the `TerraManager` instance you've created above to have the corresponding permission screen pop up.

### Call `initConnection()`

This method triggers a permission popup and establishes the connection.

From the `TerraManager` instance, call [`initConnection()`](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#initconnection) with the following arguments:

* `type`: Specify the connection type: `Connections.SAMSUNG` for Samsung Health or `Connections.HEALTH_CONNECT` for Health Connect
* `token`: A **one-time authentication token** generated from your **backend server** using Terra API. This ensures secure communication between your app and the Terra servers.
* `customPermissions`: A **set of permissions** that define what data you want to request (e.g., heart rate, steps). If empty, it defaults to all available permissions. See [Permissions mapping](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping) for every value and the Health Connect (or Samsung) data type it requests.
* `schedulerOn`: Enables background delivery, so Terra keeps syncing while your app is in the background. Defaults to `true`. On Health Connect connections, Terra also requests Health Connect's background-read permission as part of this flow. See [Set up background delivery](#set-up-background-delivery) below.

To learn more about these parameters and their different options, check the [Android SDK Reference.](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin)

{% tabs %}
{% tab title="Samsung Health" %}
{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    override fun onCreate(savedInstanceState: Bundle?) {
        // Create the Terra Manager as shown in Get a TerraManager instance
    }

    fun initialiseUserConnection() {
        if (!this::terra.isInitialized){
            throw IllegalStateException("🤯: Terra Manager not initialised yet")
        }
        val token = "your_generated_token_from_backend"

        terra.initConnection(
            connection = Connections.SAMSUNG,
            token = token,
            context = this,
            customPermissions = setOf(),
            schedulerOn = true,
            startIntent = null
        ) { success, error ->
            error?.let {
                throw IllegalStateException("🤯: ${it.message}")
            }
            Log.i("MainActivity", "Auth Success status: $success")
        }
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Health Connect" %}
{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    override fun onCreate(savedInstanceState: Bundle?) {
        // Create the Terra Manager as shown in Get a TerraManager instance
    }

    fun initialiseUserConnection() {
        if (!this::terra.isInitialized){
            throw IllegalStateException("🤯: Terra Manager not initialised yet")
        }
        val token = "your_generated_token_from_backend"

        terra.initConnection(
            connection = Connections.HEALTH_CONNECT,
            token = token,
            context = this,
            customPermissions = setOf(),
            schedulerOn = true,
            startIntent = null
        ) { success, error ->
            error?.let {
                throw IllegalStateException("🤯: ${it.message}")
            }
            Log.i("MainActivity", "Auth Success status: $success")
        }
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**`initConnection` only needs to be called a single time.**

Health Connect prohibits the permission popup to appear more than once for any given permission, so calling `initConnection` more than once will result in no action at all.

The only case where it would re-appear is if:

* you call `initConnection` with an expanded set of `customPermissions`
* the app is deleted and reinstalled
* the app requested a permission that Google did not grant for release
  {% endhint %}

#### Generate an auth token

To be able to call the `initConnection()` method, you need to pass a `token` as an argument.

This `token` is a **single-use token** created to ensure the authentication endpoint for creating a connection (and connecting the SDK to Terra's servers) does not get abused.

Generate the token with this endpoint <mark style="color:orange;">`POST`</mark>`https://api.tryterra.co/v2/auth/generateAuthToken` . Make sure to call it with your Terra `x-api-key` and `dev-id` in the headers from **your backend server.** After you generate the token, provide the response to your client side using your own logic.

{% code title="CLI" %}

```bash
curl --request POST \
  --url https://api.tryterra.co/v2/auth/generateAuthToken \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>'
```

{% endcode %}

For every parameter, see the [`/auth/generateAuthToken` endpoint](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-generateauthtoken) in the API reference.

{% hint style="warning" %}

* During the development phase, it it acceptable to place this call on the **client** side, exposing your API key in your mobile app.
* For a production implementation, **DO NOT** expose your API key this way, and make sure to **only** make this call from your **backend.**
  {% endhint %}

## Validate the connection

To ensure a connection is still valid on the client side, use the [`terra.getUserId()`](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#getuserid) method. This function is synchronous and returns the `user_id` right away or null if none exists.

{% hint style="info" %}
**Always validate the connection before using the SDK**

Check if a `user_id` exists right after **initializing the Terra SDK** to see if the connection still exists.

1. **Check if the User is Connected**
   1. If the function returns a user ID, the user is still connected, 🎉 keep vibing along!
   2. If the function returns <mark style="color:red;">`nil`</mark>, the user needs to reconnect.
2. **Re-connect if Needed**\
   If the connection is lost, you can call `terra.initConnection()` again to re-establish the connection.

Calling `terra.initConnection()` when the user is already connected or just needs a reconnection will re-establish the connection if necessary, and the user flow will remain uninterrupted.

On Apple Health, note that a `user_id` only tells you the connection exists on our side, not that your app still holds HealthKit access. Deleting an app clears its HealthKit authorization while the Terra connection survives, so the permission screen can still appear on the next `initConnection()` if iOS has not yet determined permissions for the current install.
{% endhint %}

## Set up background delivery

Background delivery keeps Health Connect data syncing while your app is in the background, rather than only while it is open. It requires `terra-android` **1.7.0 or later**, and we recommend **1.7.3 or later**. Before that, the periodic sync could be scheduled even when the user had not granted the background-read permission, so it ran without being able to read.

Passing `schedulerOn = true` to `initConnection` (the default) is all that is needed. Terra requests Health Connect's background-read permission during the connection flow and schedules the periodic sync as soon as the user grants it.

{% hint style="info" %}
If you use the Samsung-direct `co.tryterra:android-sdk` artifact described in [Install the SDK](#install-the-sdk), it is on a separate version line and does not go through Health Connect. Check with support before relying on background delivery there.
{% endhint %}

If the user declines that permission, background sync is not scheduled. Call `enableBackgroundDelivery` to prompt again:

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
terra.enableBackgroundDelivery { success, error ->
    if (success) {
        Log.i("MainActivity", "Background delivery enabled")
    } else {
        Log.w("MainActivity", "Background delivery unavailable: ${error?.message}")
    }
}
```

{% endcode %}

To read the current state without prompting the user, call `isBackgroundDeliveryAvailable` (available from `terra-android` 1.7.3):

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
terra.isBackgroundDeliveryAvailable { granted ->
    Log.i("MainActivity", "Background read granted: $granted")
}
```

{% endcode %}

It returns `false` if called before `initConnection`, which is indistinguishable from the user having declined. Call it only once a connection exists.

{% hint style="info" %}
`enableBackgroundDelivery` reports failure through its `TerraError`:

* `BackgroundDeliveryPermissionDenied`: the user declined the prompt.
* `BackgroundDeliveryNotSupported`: the Health Connect SDK is not available on the device.
* `NotAuthenticated`: called before `initConnection`.
* `UnexpectedError`: the context you passed to Terra does not extend `AppCompatActivity`, so the permission request cannot be launched.
  {% endhint %}

You now receive health data events automatically at your destination (for example, a webhook).

You can also request historical data to backfill, to verify that data exists, or as a fallback.

Check out the [Android SDK reference](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin) for details about all the functions in the SDK.

## Example app

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import co.tryterra.terra.Terra
import co.tryterra.terra.TerraManager
import co.tryterra.terra.enums.Connections

import java.lang.IllegalStateException

class MainActivity : AppCompatActivity() {
    private lateinit var terra: TerraManager

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Terra.instance("YOUR DEV ID", "REFERENCE ID", this) { manager, error ->
            error?.let{it -> 
                throw IllegalStateException("🤯: Error initialising terra ${it.message}")
            }
            terra = manager
            this.initialiseUserConnection()
        }
    }

    fun initialiseUserConnection() {
        if (!this::terra.isInitialized){
            throw IllegalStateException("🤯: Terra Manager not initialised yet")
        }
        
        if (terra.getUserId(Connections.SAMSUNG) != null){
            // User already connected
            return
        }
        
        // Initialize the connection to Samsung Health
        terra.initConnection(
            connection = Connections.SAMSUNG,   // Connecting to Samsung Health
            token = "AUTH TOKEN",                      // Token passed from backend
            context = this,                  // The activity context
            customPermissions = setOf(),  // Custom permissions set (empty set defaults to all permissions)
            schedulerOn = true,                 // Background scheduler on
            startIntent = null                  // Deprecated - always set to null
        ) { success, error ->
            error?.let {
                throw IllegalStateException("🤯: ${it.message}")
            }
            // Connection successful!
            Log.i("MainActivity", "Auth Success status: $success")
        }
    }
}
```

{% endcode %}

## Disconnect a user

In order to disconnect an SDK user, you may use [the same endpoint as for Web API-based integrations](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser), called from your backend.

## Request historical data

You can request for historical data using one of the [data retrieval functions](https://docs.tryterra.co/reference/mobile-sdks/android-kotlin#data-retrieval).

You may set `toWebhook` to false if you wish for the callback function to return the data payload on the client side.

{% code title="MainActivity.kt" lineNumbers="true" %}

```kotlin
import co.tryterra.terra.enums.Connections
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.*

fun requestData() {
    val startDate = Date.from(Instant.now().minus(1, ChronoUnit.DAYS))
    val endDate = Date()

    // Request for yesterday and today's data
    terra.getDaily(
        type = Connections.SAMSUNG,
        startDate = startDate,
        endDate = endDate,
        toWebhook = false 
    ) { success, payload, error ->
        error?.let{
            throw IllegalStateException("🤯: Error requesting data ${it.message}")    
        }
        // Process payload here
    }
}
```

{% endcode %}

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}


# React Native SDK 1.x

Connect Apple Health, Samsung Health and Health Connect users with the terra-react 1.x package: install it, initialise it, connect a user and enable background delivery.

This page shows how to integrate Apple Health, Samsung Health and Health Connect in your React Native app with `terra-react` 1.x. It covers SDK initialization, user connection, background delivery, and reading and writing data.

{% hint style="info" %}
`terra-react` 1.x is no longer the current version. For new apps, use the [React Native SDK](/mobile-sdks/react-native-sdk-2) (`@tryterra/react-native` 2.x). To move an existing app, follow [React Native upgrade guide](/mobile-sdks/react-native-migrating-to-2).
{% endhint %}

## Install and set up the plugin

1. Install the [`terra-react` package](https://www.npmjs.com/package/terra-react) using npm (`npm install terra-react`).
2. Complete the following iOS and/or Android setup.

{% tabs %}
{% tab title="iOS Setup" %}

1. In your terminal, cd to your `/ios` folder, and run `pod install` to install all the dependencies.
2. **Add Capabilities:**
   1. Healthkit > Healthkit Background Delivery
   2. Background Modes > Background processing
   3. Background modes > Background fetch
3. **Add the following keys to your info.plist:**

**Option 1: Use Xcode**

* 1\) Go to the `/ios` directory of your project, open the `.xcworkspace` in XCode.
* 2\) Go to ***info.plist,*** and add the following keys and values:

<table><thead><tr><th width="370.9501953125">Key</th><th>Value</th></tr></thead><tbody><tr><td>Privacy - Health Share Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Privacy - Health Records Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Privacy - Health Update Usage Description</td><td><p>Description of how Health data is used</p><p><strong>(Min 3 words)</strong></p></td></tr><tr><td>Permitted background task scheduler</td><td><code>co.tryterra.data.post.request</code></td></tr></tbody></table>

**Option 2: Edit info.plist directly**

* 1\) In your app project, go to your `/ios` folder
* 2\) Go to ***info.plist,*** and add the following tags:

{% code title="info.plist" lineNumbers="true" %}

```xml
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
  <string>co.tryterra.data.post.request</string>
</array>
  
<key>NSHealthClinicalHealthRecordsShareUsageDescription</key>
<string>Using TerraiOS to gather health data</string>

<key>NSHealthShareUsageDescription</key>
<string>Using TerraiOS as a mean of getting Health Data</string>

<key>NSHealthUpdateUsageDescription</key>
<string>Allow writing data to health kit</string>
```

{% endcode %}
{% endtab %}

{% tab title="Android Setup" %}

#### Access Samsung Health

Terra has a privileged partnership with Samsung that gives you direct access to the Samsung Health SDK, with no Health Connect intermediary. This is the recommended route for Samsung devices.

**1. Apply for Samsung Health access**

Submit your application through the [Samsung Health partnership portal](https://developer.samsung.com/SHealth/business-partner/m48wvqi1mt9w2w4c).

{% hint style="info" %}
While waiting for approval, you can start development immediately using the **Health Connect** route below. Switching to Samsung direct later is a version bump with no code changes.
{% endhint %}

**2. Install the Samsung-tagged SDK**

After approval, install the Samsung-tagged version of the Terra SDK:

* **React Native:** `npm install terra-react@<samsung-version>`. Find Samsung-tagged versions on the [npm versions page](https://www.npmjs.com/package/terra-react?activeTab=versions)
* **Flutter:** Use the Samsung-tagged version of `terra_flutter_bridge`. Find versions on [pub.dev](https://pub.dev/packages/terra_flutter_bridge/versions)

**3. Add the ProGuard rule (required for release builds)**

In your `android/app/proguard-rules.pro`, add:

```proguard
-keep class com.samsung.android.** { *; }
```

Without this, R8 minification will strip Samsung SDK classes and cause runtime crashes in production.

**4. Check the requirements**

* **Samsung Health** app must be installed on the device
* **Android 28 (minSDK 28)** and above
* Enable **Developer Mode** in Samsung Health on test devices (Settings > About Samsung Health > tap version number repeatedly)
* No additional manifest or Gradle changes needed: the Terra SDK handles everything

#### Access Health Connect

**1. Grant permissions in the Health Connect app**

Give all permissions between the apps you wish to read from (e.g. **Samsung Health, Google Fit, etc**) & Health Connect.

**2. Add the Health Connect capability to your app**

In your app project, go to the `/android` folder.

Include the permission tags under the Activity you wish to link the user to when they click the **privacy policy** link in the Health Connect permission screen. Here are the steps:

1. Go to your Android App's `AndroidManifest.xml`
2. Go to your **Privacy Policy** <mark style="color:purple;">`<activity>`</mark> and include the following tags under this <mark style="color:purple;">`<activity>`</mark> tag.

"Your Android manifest needs to have an Activity that displays your app's **privacy policy**, which is your app's rationale of the requested permissions, describing how the user's data is used and handled." (Health Connect)

<pre class="language-xml" data-title="AndroidManifest.xml" data-line-numbers><code class="lang-xml"><strong>&#x3C;intent-filter>
</strong>  &#x3C;action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE"/>
 &#x3C;/intent-filter>
  
&#x3C;intent-filter>
   &#x3C;action android:name="android.intent.action.VIEW_PERMISSION_USAGE"/>
  &#x3C;category android:name="android.intent.category.HEALTH_PERMISSIONS"/>
&#x3C;/intent-filter>
</code></pre>

{% hint style="warning" %}
**Apply for Health Connect access**

Before going **live** (release), you will need to apply for permissions to access the Health Connect API with Google.

1. Use this [application form](https://developer.android.com/health-and-fitness/guides/health-connect/publish/declare-access#explain-use-data-types).
2. For each permission which you are ***not*** using, please add the following lines to your AndroidManifest.xml

{% code title="AndroidManifest.xml" overflow="wrap" %}

```xml
<uses-permission android:name="android.permission.health.READ_HEART_RATE" tools:node="remove"/>
```

{% endcode %}

with `android.permission.health.XXX` for each permission you aren't using
{% endhint %}
{% endtab %}
{% endtabs %}

## Initialize the SDK

The first step is to initialize the Terra SDK.

The initialization only needs to be done once on app start (for example in your `app.tsx` or an equivalent file), and ideally every time the app is brought into the foreground. This ensures that the SDK is properly set up and ready to be used.

{% hint style="warning" %}
The SDK should be initialized every time your app is opened.

This is a necessary prerequisite for other SDK functions to run as expected
{% endhint %}

### Import the Terra plugin

In your project, you should now be able to import function from the Terra Plugin. Here is an example:

{% code title="app.tsx" lineNumbers="true" %}

```tsx
import { initTerra } from 'terra-react';
```

{% endcode %}

### Call `initTerra`

In order to interact with the SDK, you need to call `initTerra` first.

Call `initTerra()` with the following arguments:

* `devId`: Your **Developer ID** provided by Terra.
* `referenceId`: An **ID of your choice** to identify your app user.

Find more details in the SDK Reference: [React Native SDK reference](https://docs.tryterra.co/reference/mobile-sdks/react-native)

{% code title="app.tsx" lineNumbers="true" %}

```typescript
import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { initTerra } from 'terra-react';

const App = () => {
  const [initialized, setInitialized] = useState<boolean>(false);
  
  useEffect(() => {
    const initializeTerra = async () => {
      try {
        const devID = 'YOUR_DEV_ID';
        const referenceId = 'YOUR_REFERENCE_ID';
        
        const successMessage = await initTerra(devID, referenceId);
        if (successMessage.error !== null) {
          throw new Error("Terra manager failed to initialise");
        }
        // Can proceed with other Terra plugin methods
        setInitialized(true);
      } catch (error) {
        console.error('Failed to initialize Terra:', error);
      }
    };

    initializeTerra();
  }, []);

  return (
    <View>
      <Text>Welcome to the App using Terra</Text>
    </View>
  );
};

export default App;
```

{% endcode %}

This call is asynchronous. Make sure it completes before you use other SDK functions.

## Connect a user

Once Terra is initialized, you can create a connection by calling the function `initConnection()` to trigger a permission screen pop up.

### Call `initConnection()`

From `terra-react`, import `initConnection` and call the function with the following arguments:

* `type`: Specify the connection type: `Connections.APPLE_HEALTH`, `Connections.SAMSUNG`, or `Connections.HEALTH_CONNECT`
* `token`: A **one-time authentication token** generated from your backend server. This ensures secure communication between your app and the Terra servers.
* `schedulerOn`:
  * **iOS**: This parameter has no effect. Background delivery is controlled by calling `Terra.setUpBackgroundDelivery()` in your AppDelegate. See [Set up background delivery](#set-up-background-delivery) below.
  * **Android**: Enables background delivery, so Terra keeps syncing while your app is in the background. See [Set up background delivery](#set-up-background-delivery) below.
* `customPermissions`: A **set of permissions** that define what data you want to request (e.g., heart rate, steps). If empty, it defaults to all available permissions. See [Permissions mapping](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping) for every value and what it requests on each platform.

{% tabs %}
{% tab title="Apple Health (iOS)" %}
{% code title="app.tsx" lineNumbers="true" %}

```tsx
import { Connections, initConnection } from 'terra-react';

const initializeConnection = async () => {
  try {
    const token = 'example_token';

    const successMessage = await initConnection(
      Connections.APPLE_HEALTH,
      token,
      true,   // schedulerOn: no effect on iOS, see setUpBackgroundDelivery() below
      [],     // customPermissions: empty defaults to all
    );
    if (successMessage.error !== null) {
      throw new Error("Error initialising a connection");
    }
  } catch (error) {
    console.error('Connection failed:', error);
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Samsung Health (Android)" %}
{% code title="app.tsx" lineNumbers="true" %}

```tsx
import { Connections, initConnection } from 'terra-react';

const initializeConnection = async () => {
  try {
    const token = 'example_token';

    const successMessage = await initConnection(
      Connections.SAMSUNG,
      token,
      true,   // schedulerOn: enables background delivery, see Set up background delivery
      [],     // customPermissions: empty defaults to all
    );
    if (successMessage.error !== null) {
      throw new Error("Error initialising a connection");
    }
  } catch (error) {
    console.error('Connection failed:', error);
  }
}
```

{% endcode %}
{% endtab %}

{% tab title="Health Connect (Android)" %}
{% code title="app.tsx" lineNumbers="true" %}

```tsx
import { Connections, initConnection } from 'terra-react';

const initializeConnection = async () => {
  try {
    const token = 'example_token';

    const successMessage = await initConnection(
      Connections.HEALTH_CONNECT,
      token,
      true,   // schedulerOn: enables background delivery, see Set up background delivery
      [],     // customPermissions: empty defaults to all
    );
    if (successMessage.error !== null) {
      throw new Error("Error initialising a connection");
    }
  } catch (error) {
    console.error('Connection failed:', error);
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Apple Health shows the permission popup once.** Calling `initConnection()` multiple times won’t trigger the popup again unless:

* you call `initConnection` with an expanded set of `customPermissions`
* the app is deleted and reinstalled.
  {% endhint %}

{% hint style="info" %}
**`initConnection` only needs to be called a single time.**

Health Connect prohibits the permission popup to appear more than once for any given permission, so calling `initConnection` more than once will result in no action at all.

The only case where it would re-appear is if:

* you call `initConnection` with an expanded set of `customPermissions`
* the app is deleted and reinstalled
* the app requested a permission that Google did not grant for release
  {% endhint %}

{% hint style="info" %}
**WebView apps.**

* Apple HealthKit implements the permissions popup as a WebView.
* If your app is also based on a WebView, you will need to interrupt your WebView, call `initConnection`, then upon completion re-open your WebView.
  {% endhint %}

#### Generate an auth token

To be able to call the `initConnection()` method, you need to pass a `token` as an argument.

This `token` is a **single-use token** created to ensure the authentication endpoint for creating a connection (and connecting the SDK to Terra's servers) does not get abused.

Generate the token with this endpoint <mark style="color:orange;">`POST`</mark>`https://api.tryterra.co/v2/auth/generateAuthToken` . Make sure to call it with your Terra `x-api-key` and `dev-id` in the headers from **your backend server.** After you generate the token, provide the response to your client side using your own logic.

{% code title="CLI" %}

```bash
curl --request POST \
  --url https://api.tryterra.co/v2/auth/generateAuthToken \
  --header 'dev-id: <YOUR-DEV-ID>' \
  --header 'x-api-key: <YOUR-API-KEY>'
```

{% endcode %}

For every parameter, see the [`/auth/generateAuthToken` endpoint](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#post-auth-generateauthtoken) in the API reference.

{% hint style="warning" %}

* During the development phase, it it acceptable to place this call on the **client** side, exposing your API key in your mobile app.
* For a production implementation, **DO NOT** expose your API key this way, and make sure to **only** make this call from your **backend.**
  {% endhint %}

## Validate the connection

To ensure a connection is still valid on the client side, use the [`getUserId`](https://docs.tryterra.co/reference/mobile-sdks/react-native#getuserid) method. This function returns the `user_id` for the connection or null if none exists.

{% hint style="info" %}
**Always validate the connection before using the SDK**

Check if a `user_id` exists right after **initializing the Terra SDK** to see if the connection still exists.

1. **Check if the User is Connected**
   1. If the function returns a user ID, the user is still connected, 🎉 keep vibing along!
   2. If the function returns <mark style="color:red;">`nil`</mark>, the user needs to reconnect.
2. **Re-connect if Needed**\
   If the connection is lost, you can call `terra.initConnection()` again to re-establish the connection.

Calling `terra.initConnection()` when the user is already connected or just needs a reconnection will re-establish the connection if necessary, and the user flow will remain uninterrupted.

On Apple Health, note that a `user_id` only tells you the connection exists on our side, not that your app still holds HealthKit access. Deleting an app clears its HealthKit authorization while the Terra connection survives, so the permission screen can still appear on the next `initConnection()` if iOS has not yet determined permissions for the current install.
{% endhint %}

## Set up background delivery

Background delivery allows data to be synced even when your app is not brought to the foreground. iOS needs a setup step in your AppDelegate; on Android it is enabled through `initConnection`.

{% tabs %}
{% tab title="Apple Health" %}

1. Go to your `/ios` folder in the React Native project
2. Call the function `setUpBackgroundDelivery` in your AppDelegate's `didFinishLaunchingWithOptions` function

This will ensure you get updates for the user's Apple Health data automatically sent to your destination.

<pre class="language-objectivec" data-title="AppDelegate.m" data-line-numbers><code class="lang-objectivec">#import "AppDelegate.h"

#import &#x3C;React/RCTBundleURLProvider.h>
#import &#x3C;TerraiOS/TerraiOS-Swift.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"AwesomeProject";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};
  [Terra setUpBackgroundDelivery];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
<strong>}
</strong></code></pre>

{% hint style="success" %}

## iOS Background Delivery Behaviour:

* Data will still be triggered if the **app** **is** **killed** (with much lower frequency)
* Data will only be triggered when **phone** **is** **unlocked**
* Data can only be triggered where there is **network connection**
* Only enabled **Data** **Types** from [the Terra Dashboard](https://dashboard.tryterra.co) will be triggered by background delivery.
* If you are using **CustomPermissions,** please ensure the following permissions are enabled for Background Delivery to work correctly:
  * For **Daily: CustomPermissions.STEPS**
  * For **Sleep: CustomPermissions.SLEEP\_ANALYSIS**
  * For **Body: CustomPermissions.BMI, CustomPermissions.HEART\_RATE**
  * For **Activity: CustomPermissions.WORKOUT\_TYPE**
  * For **Nutrition: CustomPermissions.NUTRITION\_CALORIES**
    {% endhint %}
    {% endtab %}

{% tab title="Android (Health Connect & Samsung)" %}
No AppDelegate step is needed. Passing `true` as the third argument (`schedulerOn`) to `initConnection` enables background delivery.

On Health Connect connections, Terra requests Health Connect's background-read permission during the connection flow and schedules the periodic sync as soon as the user grants it.

{% code title="app.tsx" lineNumbers="true" %}

```typescript
import { initConnection, Connections } from 'terra-react';

await initConnection(
  Connections.HEALTH_CONNECT,
  token,
  true,   // schedulerOn: enables background delivery
  [],     // customPermissions: empty defaults to all
);
```

{% endcode %}

{% hint style="info" %}
We recommend `terra-react` 1.9.12 or later, which bundles `terra-android` 1.7.3. Earlier versions scheduled the periodic sync even when the background-read permission had not been granted, so it could run without being able to read.

If the user declines that permission, background sync is not scheduled. The React Native bridge does not currently expose a method to prompt again, so the user would need to grant it in the Health Connect app settings.
{% endhint %}
{% endtab %}
{% endtabs %}

## Optional: Filter by source app on iOS

Apple Health aggregates data from every health app on the user's device. If a user has both a cloud-based Terra connection (e.g. WHOOP, Garmin) and the same provider's companion app syncing into Apple Health, you'll receive duplicate data: once from the cloud API and once from the Apple Health SDK.

Use `setIgnoredSources` to tell the SDK to skip data from specific apps in HealthKit. Call this **once on every app launch**, after `initTerra()` completes. It is not persisted across app restarts. On Android, this function is a no-op.

```typescript
import { setIgnoredSources } from 'terra-react';

// After initTerra() completes:
setIgnoredSources(["com.whoop.app", "com.garmin.connect.mobile"]);
```

Common bundle identifiers:

| App            | Bundle identifier           |
| -------------- | --------------------------- |
| WHOOP          | `com.whoop.app`             |
| Garmin Connect | `com.garmin.connect.mobile` |
| Fitbit         | `com.fitbit.FitbitMobile`   |
| Oura           | `com.ouraring.oura`         |

{% hint style="info" %}
To find a specific app's bundle identifier, have the user check **Settings → Health → Data Access & Devices** on their iPhone.
{% endhint %}

You now receive health data events automatically at your destination (for example, a webhook).

You can also request historical data to backfill, to verify that data exists, or as a fallback.

Check out the [React Native SDK reference](https://docs.tryterra.co/reference/mobile-sdks/react-native) for details about all the functions in the SDK.

## Disconnect a user

In order to disconnect an SDK user, you may use [the same endpoint as for Web API-based integrations](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser), called from your backend.

## Request historical data

You can request for historical data using one of the [data retrieval functions.](https://docs.tryterra.co/reference/mobile-sdks/react-native#data-retrieval)

You may set `toWebhook` to false if you wish for the callback function to return the data payload on the client side.

{% code lineNumbers="true" %}

```tsx
import { Connections, getDaily } from 'terra-react';

const requestData = async () => {
  try {
    const connection = Connections.APPLE_HEALTH;
    const endDate = new Date();
    const startDate = new Date(endDate);
    startDate.setDate(startDate.getDate() - 1);

    const dataMessage = await getDaily(connection, startDate, endDate, false);
  
    if (dataMessage.error !== null) {
      throw new Error("Failed to get data for user");
    }
    if (dataMessage.success) {
      // process data here
      console.log('Daily data:', dataMessage.data);
    }
  
  } catch (error) {
    // Handle failure (network error, etc.)
    console.error('Failed to get daily data:', error);
  }
}
```

{% endcode %}

Check out the [React Native SDK reference](https://docs.tryterra.co/reference/mobile-sdks/react-native) for details about all the functions in the SDK

## Write data

You may write data into Apple Health (Health Connect not yet supported) through one of the helper functions in the SDK

* [postActivity](https://docs.tryterra.co/reference/mobile-sdks/react-native)

{% tabs %}
{% tab title="postActivity" %}
{% hint style="warning" %}
`device_data` must be passed in for postActivity to succeed.
{% endhint %}

{% code lineNumbers="true" %}

```typescript
import { Activity, postActivity, Connections } from 'terra-react';

const postActivityToAppleHealth = async () => {
  const activityPayload: Activity = {
    metadata: {
      name: 'Morning Run',
      start_time: '2024-11-01T07:30:00.000000+00:00',
      end_time: '2024-11-01T08:30:00.000000+00:00',
      type: 8, // RUNNING, see ActivityType enum in terra-react for all values
    },
    device_data: {
      name: 'Terra',
    },
    distance_data: {
      summary: { distance_meters: 5000 },
    },
    calories_data: {
      total_burned_calories: 400,
    },
  };

  const resp = await postActivity(Connections.APPLE_HEALTH, activityPayload);
  if (resp.error !== null) {
    throw new Error('Failed to post activity to Apple Health');
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% hint style="info" %}
**The mobile SDKs are only for Apple Health, Health Connect and Samsung Health.** These have no web API, so your app reads them on the phone and sends the data to Terra. Every other provider connects through the [Unified API](https://docs.tryterra.co/unified-api/getting-started) with no SDK.
{% endhint %}


# Overview

Vantage API is Terra's diagnostics platform: order blood and DNA test kits, track fulfilment, and receive lab results in FHIR format through a single API.

The Terra **Vantage API** provides a comprehensive platform for managing blood test and DNA diagnostic products, processing orders, and delivering test results. This API enables healthcare providers, laboratories and partners to integrate diagnostic testing services directly into their applications.

Vantage API allows you to focus on providing the best healthcare experience for your end users while we handle the rest.

### Why we built Vantage API

The health tech space is currently at a turning point - with the commoditisation of highly accurate wearables, metrics like step counts, HRV and sleep scores are **readily available** to most end users. However, sensors alone **cannot provide truly actionable insights** without the most important factor - **biological context**.

This is where **biomarker testing** comes in.

The process of bringing biomarker testing to your users at a commercial scale is a complicated procedure, involving commercial agreements with third party labs, convoluted delivery and collection logistics and months of navigating compliance red tape required to provide a legally viable service.

Instead, we provide a single API:

* **Effortless integration** with numerous kit suppliers.
* Bulk discounts without bulk minimum orders - we **pass on volume discounts** directly to your customers.
* **No legal or compliance headaches** - start sending white-labelled panels within days instead of months.
* Normalisation of test results into a **global format (FHIR)** for easy handling.
* **Hands-off logistics networks** for fulfilment, shipping and result delivery.

In short: plug-and-play labs infrastructure.

### How an integration works

1. **Browse the catalog** - product types → products → variants ([Core concepts](/vantage-api/core-concepts)).
2. **Place an order** for a variant, either shipped to the end user's home (`AT_HOME`) or collected at a lab draw site (`GO_TO_LAB`).
3. **Track progress via webhooks** - fulfilment events (payment, shipping) and result events (kit activated, processing, ready).
4. **Download results** as a FHIR JSON document.
5. **Acknowledge the results** after your end user has viewed them - a mandatory compliance step ([Acknowledging Results](/vantage-api/acknowledging-results)).

Start with [Account setup and authentication](/vantage-api/account-setup-and-api-keys), then walk through [Ordering your first test](/vantage-api/ordering-your-first-test) in the sandbox.

### Base URLs

{% hint style="info" %}
**Production:**

```
https://vantage.tryterra.co
```

**Sandbox:**

```
https://vantage-sandbox.tryterra.co
```

{% endhint %}

### Supported countries

* United Kingdom 🇬🇧
* USA 🇺🇸

Each environment can be limited to the products sold in one or both of these. See [Markets](/vantage-api/core-concepts#markets).

### Countries coming soon

* Germany 🇩🇪
* Spain 🇪🇸
* France 🇫🇷

### Use Vantage from your AI assistant

Your AI assistant can inspect and configure Vantage for you. Connect Claude, ChatGPT or another assistant through the [Terra MCP server](https://docs.tryterra.co/developer-tools/mcp-server), or give a coding agent the [Terra CLI](https://docs.tryterra.co/developer-tools/terra-cli/coding-agents) and the [Vantage agent skill](https://docs.tryterra.co/developer-tools/agent-skills). Then ask, for example:

* "Which Vantage webhooks failed in my sandbox this week, and why?"
* "Show me every delivery attempt for the webhooks of order 251285377984405504."
* "Limit my sandbox to products sold in the UK."
* "Which results in production are ready but not acknowledged yet?"
* "Send a test results webhook to my sandbox endpoint."
* "Which Vantage API version is my production environment on, and what changes if I upgrade?"
* "Build an order flow for our app with Vantage, starting with an at-home blood test." (coding agents)

If you are interested in getting involved as a client or supplier, please [reach out to the Terra API team](https://tryterra.co) to find out more.


# Account setup and authentication

How to get Vantage API access, authenticate your requests, and configure the webhook endpoint that receives order and result updates.

Vantage API onboarding is currently done manually. In short:

1. Contact the Terra API team (or your existing Terra contact) to request access.
2. Vantage is enabled on your Terra credentials - **sandbox first**. (New to Terra API? You'll receive a `dev-id` and API key as part of onboarding.)
3. Configure your webhook endpoint (below) and start building in sandbox. Commercial terms and production access are arranged when you are ready to go live (see [Going to production](/vantage-api/going-to-production)).

{% hint style="info" %}
Your credentials will initially only work against the sandbox environment (`https://vantage-sandbox.tryterra.co`). Production access is enabled separately.
{% endhint %}

## Authentication

Vantage API uses your standard Terra API credentials - the same `dev-id` and API key you use with other Terra API products (visible in your [Terra dashboard](https://dashboard.tryterra.co)). You can present them in either of two ways:

**Option 1 - HTTP Basic auth (recommended).** Username = your `dev-id`, password = your API key:

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/products' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

`curl -u` builds the header for you. If your HTTP client does not, base64-encode `dev-id:api-key` yourself and send it as `Authorization: Basic <encoded>`:

```bash
echo -n 'YOUR_DEV_ID:YOUR_API_KEY' | base64
# then send: Authorization: Basic <output of the command above>
```

**Option 2 - header pair.** The same `dev-id` + `x-api-key` headers used across Terra API:

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/products' \
  --header 'dev-id: YOUR_DEV_ID' \
  --header 'x-api-key: YOUR_API_KEY'
```

Both are accepted on every authenticated endpoint. A wrong or unknown credential returns `401`; a suspended account or an account without Vantage access returns `403`. See [Errors](/vantage-api/errors).

## Configure your webhook endpoint

Order and result progress is delivered to a single HTTPS webhook URL per environment (sandbox and production each hold their own). Set it once during setup:

{% tabs %}
{% tab title="cURL" %}

```bash
curl --request PATCH \
  'https://vantage-sandbox.tryterra.co/api/v1/clients/webhook-url' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "webhook_url": "https://your-domain.com/webhooks/terra"
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://vantage-sandbox.tryterra.co/api/v1/clients/webhook-url"

response = requests.patch(
    url,
    auth=("YOUR_DEV_ID", "YOUR_API_KEY"),
    json={"webhook_url": "https://your-domain.com/webhooks/terra"},
)

print(response.status_code)
print(response.text)
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	url := "https://vantage-sandbox.tryterra.co/api/v1/clients/webhook-url"

	payload := map[string]string{
		"webhook_url": "https://your-domain.com/webhooks/terra",
	}
	jsonData, err := json.Marshal(payload)
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonData))
	if err != nil {
		panic(err)
	}
	req.SetBasicAuth("YOUR_DEV_ID", "YOUR_API_KEY")
	req.Header.Add("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

Notes:

* The URL **must be HTTPS** and must not contain credentials (`https://user:pass@...` returns `400`). Sending an empty string (`""`) clears it, which stops webhook delivery.
* `GET /api/v1/clients/webhook-url` returns the currently registered URL for the environment you call it on.
* Webhooks are signed; verify the signature on every delivery. See [Webhooks](/vantage-api/webhooks).

Once your webhook endpoint is configured, you are ready for [Ordering your first test](/vantage-api/ordering-your-first-test).


# Core concepts

The Vantage API data model: catalog structure, orders and order items, recipients and test takers, status lifecycles, and conventions used across all endpoints.

## The catalog: product types → products → variants

The catalog is three levels deep:

| Level            | What it is                                                             | Example                                                           |
| ---------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------- |
| **Product type** | The broadest category                                                  | Blood Test, DNA Test                                              |
| **Product**      | An offering within a type                                              | An at-home blood test kit from a given supplier                   |
| **Variant**      | The exact configuration an end user receives - **the thing you order** | The "Inflammation" panel (hs-CRP + Vitamin D), 3-5 day turnaround |

A product's `description` is a [rich text document](/vantage-api/rich-text) from API version `2026-10-29`, and a string before it.

You browse with `GET /api/v1/products` (types) → `GET /api/v1/products/{product_type_id}` (products), and you order a `variant_id`. Each product in that listing carries its variants nested under `variants`, so one call per product type lists everything you can order. `GET /api/v1/products/{product_id}/variants` remains available for the variants of a single product. A variant advertises which collection methods it supports in `available_collection_types` (an array of strings: `"AT_HOME"`, `"GO_TO_LAB"`).

For display, a variant carries typed fields, [added in API version `2026-10-01`](/vantage-api/versioning):

* `name`: the variant's name, as the supplier states it.
* `description`: the supplier's blurb. Omitted when there is none.
* `collection_method`: how the sample is taken, `finger_prick` or `venous_draw`. Omitted when the supplier states a method outside that vocabulary.
* `turnaround_days`: the stated lab turnaround as `{ "min": 3, "max": 5 }`. Omitted when none is stated.
* `requires_activation`: always present. When `true`, show the kit-activation step: the sample is not processed until the kit is activated.
* `availability`: a string, one of `unknown`, `in_stock` or `out_of_stock`. Products carry the same field.
* `biomarkers`: what the kit measures, in panel order. Each entry has a `name`, and may carry `code`, which matches the Observation code in the result bundle, and a `loinc` code. Always present, empty when the panel is not catalogued yet. Each entry also explains the biomarker for people without a medical background:

  * `summary`: one line of plain text, for a table row.
  * `description`: a fuller explanation, as a [rich text document](/vantage-api/rich-text) in every API version.
  * `source_url`: the page both are copied from, word for word: the U.S. National Cancer Institute's Dictionary of Cancer Terms or MedlinePlus (U.S. National Library of Medicine). Credit it with a link wherever you show the text.

  All three are always present, and `null` together when no source explains the biomarker.

A trimmed product from `GET /api/v1/products/1`:

```json
{
  "id": 10002,
  "name": "Advanced Blood Panel",
  "availability": "in_stock",
  "variants": [
    {
      "id": 100041,
      "name": "Inflammation",
      "description": "Inflammation marker testing",
      "collection_method": "venous_draw",
      "turnaround_days": { "min": 3, "max": 5 },
      "requires_activation": true,
      "availability": "in_stock",
      "biomarkers": [
        {
          "name": "hs-CRP",
          "summary": "A protein that is made by the liver when there is inflammation or tissue damage in the body. …",
          "description": { "type": "root", "children": [ … ] },
          "source_url": "https://www.cancer.gov/publications/dictionaries/cancer-terms/def/c-reactive-protein"
        },
        { "name": "Vitamin D", "summary": null, "description": null, "source_url": null }
      ],
      "available_collection_types": ["AT_HOME"]
    }
  ]
}
```

Your catalog is scoped to your contract: browsing returns only the panels and fulfilment options your account is entitled to, and orders for anything outside it are rejected. To add panels to your contract, contact the Terra team. Within your entitlements, you can additionally curate which products your catalog reads return - see [Managing orders](/vantage-api/managing-orders#curating-your-catalog).

### Markets

Vantage sells in two markets, the **UK** and the **US**, and each offers different products. Each environment has its own markets:

* Until an environment's markets are set, it sees every market's products, including markets added later.
* Once they are set, catalog reads leave out products not sold in them: `GET /api/v1/products/{id}` (with or without `show_all`) omits them, and `GET /api/v1/products/{id}/variants` returns `404` for one. Ordering one returns `403`.
* **Testing environments** choose their markets in the dashboard, under Vantage → Settings → Markets.
* **Production environments** have their markets set by Terra during account setup. Tell your Terra contact which markets you sell in.

Markets and [curation](/vantage-api/managing-orders#curating-your-catalog) combine: a product must be in one of your markets and enabled in your catalog to be listed or ordered.

## Orders and order items

An **order** is one purchase: it has a recipient, a collection type, an address, and one or more **order items** (one per `variant_id` + quantity). Everything result-related happens **per order item**: kit activation, result statuses, result downloads, and acknowledgment are all keyed by `order_item_id`, not `order_id`.

* `client_order_reference_id` - **your** unique identifier for the order, supplied when you create it. Use it to reconcile webhooks and REST reads with your own system. For retry-safe creation, send an `Idempotency-Key` header - the reference id alone does not deduplicate.
* `order_id`, `order_item_id`, `recipient_id`, `test_taker_id` - Terra-generated identifiers.

{% hint style="warning" %}
**Treat IDs as strings.** All Vantage identifiers are 64-bit values serialized as JSON strings (e.g. `"251285377984405504"`). Parsing them as floating-point numbers (the default in JavaScript) silently corrupts them. Store and compare them as strings.
{% endhint %}

## Recipient vs test taker

* The **recipient** is the person the order is placed for - name, date of birth, gender at birth, email, phone. You provide it at order time.
* The **test taker** is the person who actually takes the test. For variants with `requires_activation: true`, the test taker registers themselves during activation (and may differ from the recipient, supplier-permitting). Terra assigns a `test_taker_id` at that point and includes it in every result webhook.

You need the `test_taker_id` to fetch and acknowledge results - capture it from the result webhooks (or from `GET /api/v1/orders/{orderID}`).

## Collection types

Every order has a `collection_type` that determines how the sample is collected and which address field the order requires:

| `collection_type` | Meaning                                                  | Address field           |
| ----------------- | -------------------------------------------------------- | ----------------------- |
| `AT_HOME`         | Kit shipped to the recipient, who self-collects          | `shipping_address`      |
| `GO_TO_LAB`       | Sample drawn at a lab draw site (Patient Service Center) | `requested_lab_address` |

See [Test Collection Methods](/vantage-api/test-collection-methods).

## Status lifecycles

An order carries a fulfilment status; each order item carries a results status.

**Order (fulfilment) statuses**, as returned by the REST API:

```
order.payment_processing → order.payment_complete | order.payment_failed | order.cancelled
order.payment_complete   → order.processing | order.cancelled
order.processing         → order.delayed | order.delivery_fulfilled | order.cancelled
order.delayed            → order.delivery_fulfilled | order.cancelled
order.delivery_fulfilled → order.completed
```

New orders start at `order.payment_processing`.

**Order item (results) statuses:**

```
results.awaiting_sample          → results.kit_activated | results.sample_rejected
results.kit_activated            → results.sample_processing_in_lab | results.sample_rejected
results.sample_processing_in_lab → results.partial_results_ready | results.results_ready
                                   | results.lab_processing_error | results.escalation_raised
                                   | results.sample_rejected
results.partial_results_ready    → results.results_ready | results.escalation_raised
results.results_ready            → results.escalation_raised
```

{% hint style="warning" %}
REST endpoints and webhook payloads use the same `order.*` vocabulary for fulfilment statuses (and the same `results.*` vocabulary for results statuses) - a status seen on a webhook can be matched verbatim against any REST read of the order.
{% endhint %}

## Escalation levels

Results carrying clinical escalation include an `escalation_level`, one of (in ascending severity):

`not_escalated`, `very_low`, `low`, `medium`, `high`, `very_high`

Escalated results also carry an `acknowledgment_due_by` timestamp - see [Acknowledging Results](/vantage-api/acknowledging-results).

## Conventions

* **Money** is integer cents (`price_cents`, `total_cents`); **currency** is an ISO 4217 numeric code (`840` = USD, `978` = EUR, `826` = GBP).
* **Phone numbers are a single E.164 string everywhere**: the industry-standard format used by Stripe, Twilio and FHIR. Send `phone_number` as a `+`-prefixed E.164 string (`"+14155551234"`); reads and webhook `test_taker` payloads return the same string. There is no separate recipient `country_code` field.
* **Timestamps** in webhook payloads (`timestamp`) are Unix seconds; REST timestamps are RFC 3339 strings.
* **Errors** follow RFC 7807 problem-detail format - see [Errors](/vantage-api/errors).
* **List endpoints** (`GET /api/v1/orders`, `GET /api/v1/results`, `GET /api/v1/webhook-deliveries`) are keyset-paginated: pass the returned `next_cursor` as `?cursor=` for the next page; a page without `next_cursor` is the last one.


# Ordering your first test

Place your first sandbox order in a few minutes: browse the catalog, order a test kit, and watch the fulfilment webhooks arrive.

**Prerequisites:** Vantage sandbox credentials and a configured webhook endpoint ([Account setup and authentication](/vantage-api/account-setup-and-api-keys)). All examples below run against the sandbox.

Key terminology (full detail in [Core concepts](/vantage-api/core-concepts)), with a consumer-electronics analogy:

* `Product type`: the broadest category of offering (e.g. iPhone, MacBook, iPad)
* `Product`: individual products within each type (e.g. iPhone 17 Pro, iPhone 16 Pro Max)
* `Product variant`: the specific configuration an end user receives (e.g. iPhone 17 White 256GB) - **this is what you order**

{% hint style="info" %}
**Production:** `https://vantage.tryterra.co` | **Sandbox:** `https://vantage-sandbox.tryterra.co`
{% endhint %}

### Explore product types

{% tabs %}
{% tab title="cURL" %}

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/products' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://vantage-sandbox.tryterra.co/api/v1/products"
response = requests.get(url, auth=("YOUR_DEV_ID", "YOUR_API_KEY"))
print(response.text)
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    url := "https://vantage-sandbox.tryterra.co/api/v1/products"

    req, _ := http.NewRequest("GET", url, nil)
    req.SetBasicAuth("YOUR_DEV_ID", "YOUR_API_KEY")

    res, _ := http.DefaultClient.Do(req)
    defer res.Body.Close()

    body, _ := io.ReadAll(res.Body)
    fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="200" %}

```json
[
  {
    "id": 1,
    "name": "Blood Test",
    "description": "Diagnostic blood panels and biomarker tests"
  }
]
```

{% endtab %}
{% endtabs %}

### Explore products within a product type

Suppose we want a blood test. `1` is the **product type** ID from the response above:

{% tabs %}
{% tab title="cURL" %}

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/products/1' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

product_type_id = 1
url = f"https://vantage-sandbox.tryterra.co/api/v1/products/{product_type_id}"
response = requests.get(url, auth=("YOUR_DEV_ID", "YOUR_API_KEY"))
print(response.text)
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="200" %}

```json
[
  {
    "id": 10002,
    "product_type_id": 1,
    "name": "Advanced Blood Panel",
    "description": "At-home blood test kit with lab processing (placeholder).",
    "base_price_cents": 4999,
    "currency": 840,
    "availability": "in_stock",
    "images": [],
    "variants": [
      {
        "id": 100041,
        "product_id": 10002,
        "product_type_id": 1,
        "name": "Inflammation",
        "description": "Inflammation marker testing",
        "collection_method": "venous_draw",
        "turnaround_days": { "min": 3, "max": 5 },
        "requires_activation": true,
        "availability": "in_stock",
        "biomarkers": [{ "name": "hs-CRP" }, { "name": "Vitamin D" }],
        "available_collection_types": ["AT_HOME"],
        "supported_ship_to_countries": ["US"],
        "price_cents": 7900,
        "currency": 840
      }
    ]
  }
]
```

{% endtab %}
{% endtabs %}

### Explore product variants

Now let's choose the exact blood test to order. `10002` is the product ID from the response above:

{% tabs %}
{% tab title="cURL" %}

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/products/10002/variants' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

product_id = 10002
url = f"https://vantage-sandbox.tryterra.co/api/v1/products/{product_id}/variants"
response = requests.get(url, auth=("YOUR_DEV_ID", "YOUR_API_KEY"))
print(response.text)
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="200" %}

```json
[
  {
    "id": 100041,
    "product_id": 10002,
    "product_type_id": 1,
    "name": "Inflammation",
    "description": "Inflammation marker testing",
    "collection_method": "venous_draw",
    "turnaround_days": { "min": 3, "max": 5 },
    "requires_activation": true,
    "availability": "in_stock",
    "biomarkers": [{ "name": "hs-CRP" }, { "name": "Vitamin D" }],
    "available_collection_types": ["AT_HOME"],
    "supported_ship_to_countries": ["US"],
    "price_cents": 7900,
    "currency": 840
  }
]
```

{% endtab %}
{% endtabs %}

Use `biomarkers` to show what the kit measures. Each entry has a `name`, and carries `code` and `loinc` when they are catalogued. `turnaround_days` is the supplier's stated lab turnaround, in days. `requires_activation` tells you whether your flow needs the kit-activation step: when `true`, the sample is not processed until the kit is activated. `availability` is a string, one of `unknown`, `in_stock` or `out_of_stock`.

Check `available_collection_types` before offering a collection method to a user - not every variant supports both.

### Order a test kit

Let's order one "Inflammation" kit (`variant_id` `100041`) as an `AT_HOME` order:

* An order needs: your own `client_order_reference_id`, a `collection_type`, the recipient, an address, and the items (`variant_id` + `quantity`).
* `AT_HOME` orders take a `shipping_address`; `GO_TO_LAB` orders take a `requested_lab_address` instead - see [Test Collection Methods](/vantage-api/test-collection-methods).
* Prices are integer cents; `currency` is ISO 4217 numeric (`840` = USD).

{% tabs %}
{% tab title="cURL" %}

```bash
curl --request POST 'https://vantage-sandbox.tryterra.co/api/v1/orders' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data-raw '{
    "client_order_reference_id": "TEST-ORDER-001",
    "collection_type": "AT_HOME",
    "recipient": {
        "first_name": "John",
        "last_name": "Smith",
        "email": "john.smith@example.com",
        "phone_number": "+14155551234",
        "date_of_birth": "1995-10-10",
        "gender_at_birth": "male"
    },
    "shipping_address": {
        "address_line_1": "123 Market Street",
        "city": "San Francisco",
        "administrative_area": "CA",
        "country_code": "US",
        "postal_code": "94102"
    },
    "items": [
        {
            "variant_id": "100041",
            "quantity": 1
        }
    ]
}'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://vantage-sandbox.tryterra.co/api/v1/orders"

payload = {
    "client_order_reference_id": "TEST-ORDER-001",
    "collection_type": "AT_HOME",
    "recipient": {
        "first_name": "John",
        "last_name": "Smith",
        "email": "john.smith@example.com",
        "phone_number": "+14155551234",
        "date_of_birth": "1995-10-10",
        "gender_at_birth": "male",
    },
    "shipping_address": {
        "address_line_1": "123 Market Street",
        "city": "San Francisco",
        "administrative_area": "CA",
        "country_code": "US",
        "postal_code": "94102",
    },
    "items": [
        {
            "variant_id": "100041",
            "quantity": 1,
        }
    ],
}

response = requests.post(url, auth=("YOUR_DEV_ID", "YOUR_API_KEY"), json=payload)
print(response.status_code)
print(response.text)
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="201" %}

```json
{
  "order_id": "251285377984405504",
  "recipient_id": "251285377984405505",
  "order_items": [
    {
      "order_id": "251285377984405504",
      "order_item_id": "251285377984405507",
      "variant_id": "100041",
      "product_type_id": "1",
      "price_per_item_cents": 7900,
      "quantity": 1,
      "currency": 840,
      "results_status": "results.awaiting_sample"
    }
  ],
  "order_status": "order.payment_processing"
}
```

{% endtab %}

{% tab title="400" %}

```json
{
  "type": "https://api.terra-diagnostics.com/errors/validation-error",
  "title": "Validation Failed",
  "status": 400,
  "detail": "One or more required fields are missing or invalid",
  "instance": "/api/v1/orders",
  "invalid_fields": [
    {
      "field": "PhoneNumber",
      "message": "PhoneNumber is not a valid phone number for the provided country code",
      "tag": "phone_with_country",
      "value": "1234567890"
    }
  ]
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
IDs in order responses and webhooks (`order_id`, `order_item_id`, `recipient_id`, `test_taker_id`) are JSON **strings** - store them as strings. See [Core concepts](/vantage-api/core-concepts).
{% endhint %}

Ordering a variant that does not exist returns a `404` problem-detail response; ordering a product you have disabled in your catalog returns `403`. See [Errors](/vantage-api/errors).

### Watch the fulfilment webhooks arrive

As the order progresses, `order.status_changed` webhooks land on your configured endpoint (in sandbox too). For example, once delivery details are available:

```json
{
  "event_type": "order.status_changed",
  "event_id": "249956485092777984",
  "timestamp": 1763661470,
  "data": {
    "order_id": "251285377984405504",
    "status": "order.delivery_fulfilled",
    "tracking_number": "KnD3d5PMZyq5ulNcWkrq"
  }
}
```

{% hint style="info" %}
Webhook payloads use the same `order.*` status vocabulary as REST reads of the order - see [Core concepts](/vantage-api/core-concepts#status-lifecycles). In sandbox, payloads additionally carry `supplier_item_id`, which you need for simulating kit activation.
{% endhint %}

Verify the signature on every webhook you receive - see [Webhooks](/vantage-api/webhooks).

### Next: get results

In production you would now wait for the physical kit to reach your user. In sandbox, continue to [Working with Sandbox](/vantage-api/working-with-sandbox) to simulate the rest of the journey - kit activation, lab processing, and results - and to fetch and acknowledge the result.


# Sandbox

Simulate the full kit journey in sandbox - either by driving lifecycle events directly with the simulate endpoint, or by walking the realistic supplier flow with kit activation - then fetch and acknow

The sandbox environment (`https://vantage-sandbox.tryterra.co`) lets you exercise the entire integration - ordering, fulfilment webhooks, kit activation, results, and acknowledgment - without shipping a physical kit. Webhooks are delivered to your configured endpoint exactly as in production.

There are two ways to move a sandbox order through its lifecycle:

1. **The simulate endpoint** - drive any lifecycle event on demand. Deterministic, scriptable, ideal for automated tests.
2. **The simulated supplier flow** - the sandbox supplier automatically progresses your order on timers, including the end-user kit-activation step. Ideal for experiencing the realistic journey.

Both start the same way: place an order as shown in [Ordering your first test](/vantage-api/ordering-your-first-test).

## The simulate endpoint

`POST /api/v1/orders/{orderID}/simulate` applies one lifecycle event to your order exactly as a real supplier update would: the status history is recorded and the corresponding **signed webhook is delivered** to your registered endpoint.

```bash
curl --request POST \
  'https://vantage-sandbox.tryterra.co/api/v1/orders/251285377984405504/simulate' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{ "event": "delivery_fulfilled" }'
```

```json
{ "order_id": "251285377984405504", "applied_event": "delivery_fulfilled" }
```

* `event` is one of: `payment_complete`, `payment_failed`, `processing`, `delayed`, `cancelled`, `delivery_fulfilled`, `completed` (order events), `kit_activated`, `sample_processing_in_lab`, `sample_rejected`, `partial_results_ready`, `results_ready`, `lab_processing_error`, `escalation_raised` (result events).
* Result events target an order item; pass `"order_item_id"` to pick one when the order has several.
* Only valid forward transitions are accepted - an out-of-order event returns `422` (see the lifecycle graphs in [Core concepts](/vantage-api/core-concepts#status-lifecycles)).
* `results_ready` also stores a sample result document, so the download and acknowledge flows below work end to end.

{% hint style="info" %}
The simulate endpoint exists **only outside production** - calling it in production returns `403`.
{% endhint %}

A minimal happy path for a fresh `AT_HOME` order (which starts at `order.payment_processing`):

```
payment_complete → processing → delivery_fulfilled → kit_activated → sample_processing_in_lab → results_ready
```

then fetch and acknowledge the result (steps 4-5 below).

## The simulated supplier flow

The sandbox supplier automatically progresses orders the way a real kit journey would:

### Shipping

Within a minute or so of placing the order you receive `order.status_changed` webhooks, ending with `order.delivery_fulfilled` carrying a tracking number and - **sandbox only** - the `supplier_item_id` you'll need for activation:

{% tabs %}
{% tab title="Sandbox" %}

```json
{
  "event_type": "order.status_changed",
  "event_id": "249956485092777984",
  "timestamp": 1763661470,
  "data": {
    "order_id": "251285377984405504",
    "status": "order.delivery_fulfilled",
    "supplier_item_id": "249602021676720128",
    "tracking_number": "KnD3d5PMZyq5ulNcWkrq"
  }
}
```

{% endtab %}

{% tab title="Production" %}

```json
{
  "event_type": "order.status_changed",
  "event_id": "249956485092777984",
  "timestamp": 1763661470,
  "data": {
    "order_id": "251285377984405504",
    "status": "order.delivery_fulfilled",
    "tracking_number": "KnD3d5PMZyq5ulNcWkrq"
  }
}
```

{% endtab %}
{% endtabs %}

### Kit activation (end-user step)

Some suppliers require the end user to activate their kit before the lab will process it - typically by scanning a QR code on the packaging that opens an activation page. To stand in for your end user scanning the QR code, open the activation URL in a browser, using the `supplier_item_id` from the webhook above as `kit_id`:

```
https://vantage-sandbox.tryterra.co/api/v1/orders/activate?kit_id=249602021676720128
```

Fill out the test-taker details on the page and activate the kit. A successful activation:

* emits a `results.kit_activated` webhook containing the newly assigned **`test_taker_id`** - capture it, you need it to fetch and acknowledge results;
* moves the order item to `results.kit_activated`.

<div><figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-c62aeb56133187f3abac81f609bd00989abd85ff%2Fvantage-kit-activation-form.png?alt=media" alt="Kit activation form"><figcaption></figcaption></figure> <figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-090696aac973add3c355173621af1d300ef1d931%2Fvantage-kit-activation-confirmation.png?alt=media" alt="Kit activation confirmation"><figcaption></figcaption></figure></div>

(In production the QR code embeds the same URL on `vantage.tryterra.co`; the browser visit is only a sandbox stand-in for the scan. Activation can also be performed programmatically - `POST /api/v1/orders/activate` - if you build your own activation UI.)

### Lab processing and results

After activation, the sandbox automatically sends the remaining result webhooks at 1-2 minute intervals:

{% tabs %}
{% tab title="Lab processing" %}

```json
{
  "event_type": "order_item.results_status_change",
  "event_id": "249958648347009024",
  "timestamp": 1763661985,
  "data": {
    "order_id": "251285377984405504",
    "order_item_id": "251285377984405507",
    "results_status": "results.sample_processing_in_lab",
    "variant_id": "100041",
    "test_taker": {
      "test_taker_id": "257837964552478720",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone_number": "+14155551234"
    }
  }
}
```

{% endtab %}

{% tab title="Results ready" %}

```json
{
  "event_type": "order_item.results_status_change",
  "event_id": "249958796259139584",
  "timestamp": 1763662021,
  "data": {
    "order_id": "251285377984405504",
    "order_item_id": "251285377984405507",
    "results_status": "results.results_ready",
    "variant_id": "100041",
    "test_taker": {
      "test_taker_id": "257837964552478720",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone_number": "+14155551234"
    }
  }
}
```

{% endtab %}
{% endtabs %}

The sandbox happy path delivers `results.results_ready`; use the simulate endpoint to exercise `results.sample_rejected` and the other failure paths deliberately.

### Fetching results

Fetch a presigned download URL with the `order_item_id` and the `test_taker_id` (both **required**):

{% tabs %}
{% tab title="cURL" %}

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/results/251285377984405507?test_taker_id=257837964552478720' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

order_item_id = "251285377984405507"
test_taker_id = "257837964552478720"
url = f"https://vantage-sandbox.tryterra.co/api/v1/results/{order_item_id}"

response = requests.get(
    url,
    auth=("YOUR_DEV_ID", "YOUR_API_KEY"),
    params={"test_taker_id": test_taker_id},
)
print(response.text)
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	orderItemID := "251285377984405507"
	testTakerID := "257837964552478720"
	url := fmt.Sprintf(
		"https://vantage-sandbox.tryterra.co/api/v1/results/%s?test_taker_id=%s",
		orderItemID, testTakerID,
	)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		panic(err)
	}
	req.SetBasicAuth("YOUR_DEV_ID", "YOUR_API_KEY")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="200" %}

```json
{
  "download_url": "https://storage.googleapis.com/.../normalised.json?X-Goog-Signature=...",
  "format": "json",
  "expires_at": "2025-11-19T19:08:04.400Z"
}
```

{% endtab %}
{% endtabs %}

The `download_url` is valid for **15 minutes**. Re-call this endpoint to mint a fresh URL rather than storing it. The downloaded document is a FHIR Bundle - see [Results](/vantage-api/results).

### Acknowledge the results

After your end user has actually viewed their results, record their confirmation (again with both `order_item_id` and `test_taker_id`):

```bash
curl --request POST \
  'https://vantage-sandbox.tryterra.co/api/v1/results/251285377984405507/acknowledge?test_taker_id=257837964552478720' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

```json
{ "status": "acknowledged" }
```

{% hint style="danger" %}
Acknowledgment is a mandatory compliance step with liability consequences, and it must be triggered by an explicit end-user action - never automatically. Read [Acknowledging Results](/vantage-api/acknowledging-results) before building this flow.
{% endhint %}


# Managing orders

Track orders after placement: fetch full order detail with status history, list and filter orders and results, and curate which products your catalog returns.

Webhooks are the primary way to follow an order ([Webhooks](/vantage-api/webhooks)), but the REST API gives you the full current state at any time - useful for reconciliation, support tooling, and recovering from missed webhooks.

## Get one order

`GET /api/v1/orders/{orderID}` returns the complete order: items, recipient, addresses, financials, and a full status history.

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/orders/251285377984405504' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

```json
{
  "order_id": "251285377984405504",
  "client_id": "terra_client_abc123",
  "client_order_reference_id": "TEST-ORDER-001",
  "collection_type": "AT_HOME",
  "order_status": "order.delivery_fulfilled",
  "recipient": {
    "id": "251285377984405505",
    "first_name": "John",
    "last_name": "Smith",
    "email": "john.smith@example.com",
    "phone_number": "+14155551234",
    "date_of_birth": "1995-10-10",
    "gender_at_birth": "male"
  },
  "shipping_address": {
    "address_line_1": "123 Market Street",
    "city": "San Francisco",
    "administrative_area": "CA",
    "country_code": "US",
    "postal_code": "94102"
  },
  "items": [
    {
      "order_id": "251285377984405504",
      "order_item_id": "251285377984405507",
      "variant_id": "100041",
      "product_type_id": "1",
      "price_per_item_cents": 7900,
      "quantity": 1,
      "currency": 840,
      "results_status": "results.kit_activated",
      "supplier_item_id": "249602021676720128",
      "test_taker_ids": ["257837964552478720"]
    }
  ],
  "order_financials": {
    "currency": 840,
    "total_cents": 7900
  },
  "status_history": [
    {
      "status": "results.kit_activated",
      "order_item_id": "251285377984405507",
      "changed_at": "2026-07-20T14:12:09Z"
    },
    {
      "status": "order.delivery_fulfilled",
      "changed_at": "2026-07-20T13:58:41Z"
    },
    {
      "status": "order.processing",
      "changed_at": "2026-07-20T13:55:02Z"
    }
  ]
}
```

Useful properties:

* `status_history` is the lifecycle timeline, newest first, mixing order-level fulfilment events and per-item results events. Escalation entries additionally carry `escalation_level` and `acknowledgment_due_by`.
* `items[].supplier_item_id` - the supplier-side kit ID, recoverable here even if you missed the webhook that carried it.
* `items[].test_taker_ids` - test takers registered on the item (present once a kit is activated); this is where to recover a `test_taker_id` you failed to capture from a webhook.
* Requesting an order that is not yours returns `404`.

## List orders

`GET /api/v1/orders` is a keyset-paginated index, newest first:

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/orders?limit=25&status=order.processing,order.delayed' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

Query parameters:

| Parameter                   | Meaning                                                                                                    |
| --------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `limit`                     | Page size, 1-100 (default 25)                                                                              |
| `cursor`                    | The `next_cursor` from the previous page                                                                   |
| `order`                     | `desc` for newest first (default), `asc` for oldest first                                                  |
| `since`, `until`            | Only orders created at/after, or at/before, this RFC 3339 timestamp                                        |
| `status`                    | Only orders in these statuses (e.g. `order.processing`); an unknown status returns `400`                   |
| `order_id`                  | Only these orders                                                                                          |
| `variant_id`                | Only orders with an item of one of these variants                                                          |
| `client_order_reference_id` | Only orders with exactly this reference                                                                    |
| `recipient_name`            | Only orders whose recipient's full name contains this text, ignoring case                                  |
| `recipient_email`           | Only orders whose recipient's email contains this text, ignoring case                                      |
| `collection_type`           | `AT_HOME` or `GO_TO_LAB`                                                                                   |
| `missing`                   | `true` = only delivered/completed orders that still have items without results - your "chase these up" set |

Filters combine: an order must match every filter you send. `status`, `order_id` and `variant_id` take up to 100 values, repeated (`status=a&status=b`) or joined with commas, and match any of them. Send the same `order` and filters with every page's `cursor`.

The response is `{ "data": [...], "has_more": true, "next_cursor": "..." }`; `has_more` is `false` and `next_cursor` is `null` on the last page.

## List results

`GET /api/v1/results` is the same pattern for result activity - one row per order item, including `results_status`, `is_acknowledged`, and `test_taker_id`:

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/results?status=results.results_ready&is_acknowledged=false' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

Query parameters:

| Parameter                   | Meaning                                                                                              |
| --------------------------- | ---------------------------------------------------------------------------------------------------- |
| `limit`, `cursor`, `order`  | As for orders                                                                                        |
| `since`, `until`            | Only items updated at/after, or at/before, this RFC 3339 timestamp                                   |
| `status`                    | Only items in these results statuses (e.g. `results.results_ready`); an unknown status returns `400` |
| `is_acknowledged`           | `true` or `false`: only results you have, or have not, acknowledged                                  |
| `order_id`                  | Only items of these orders                                                                           |
| `variant_id`                | Only items of these variants                                                                         |
| `client_order_reference_id` | Only items of orders with exactly this reference                                                     |

`status`, `order_id` and `variant_id` take multiple values the same way as on orders. Use `status=results.results_ready&is_acknowledged=false` to find results that are ready but not yet acknowledged.

## Curating your catalog

By default, catalog reads return every product Terra offers you. If you only want to expose a subset to your application, save a selection:

```bash
curl --request PUT 'https://vantage-sandbox.tryterra.co/api/v1/products/selection' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{ "product_ids": ["10002", "10003"] }'
```

* This is a **full-set write**: listed products become enabled, every other product becomes disabled.
* With no selection saved, everything is enabled. Products added to the global catalog after your last save default to enabled until you save again.
* Disabled products disappear from your normal catalog reads, and ordering them returns `403`.
* To see the full catalog with per-product `enabled` flags (e.g. to build a curation UI), pass `?show_all=true` to `GET /api/v1/products/{id}` or `GET /api/v1/products/{id}/variants`. The variants nested on each product in `GET /api/v1/products/{id}` follow the same rule.
* Curation applies within your environment's [markets](/vantage-api/core-concepts#markets): products outside them are left out even with `?show_all=true`, and a selection only enables products in your current markets, so changing markets later never finds products curated out.


# Test collection methods

AT\_HOME vs GO\_TO\_LAB orders: which address fields each requires, how lab routing works, and how to find nearby lab draw sites.

## Overview

Depending on the supplier and the product, a test can support multiple collection methods - ways for the end user to provide the sample. A variant advertises what it supports in `available_collection_types`; every order picks one via `collection_type`.

| `collection_type` | Meaning                                                                                                 |
| ----------------- | ------------------------------------------------------------------------------------------------------- |
| `AT_HOME`         | Kits are sent to the end user's home. They follow the kit instructions to self-collect.                 |
| `GO_TO_LAB`       | The end user visits a lab draw site (Patient Service Center), where a professional collects the sample. |

The collection type determines which address field the order requires:

* `AT_HOME` → `shipping_address` (where to ship the kit)
* `GO_TO_LAB` → `requested_lab_address` (used to route the order to the closest available lab)

## Where a test can be ordered

Every variant advertises the countries it can be ordered in as `supported_ship_to_countries` (ISO-3166 alpha-2 codes). For `AT_HOME` this is the kit's shipping destination; for `GO_TO_LAB`, the country of the requested lab:

```json
{
  "id": 100011,
  "name": "Standard Kit",
  "available_collection_types": ["AT_HOME"],
  "supported_ship_to_countries": ["GB"]
}
```

Gate your address form (or country picker) on this list. Orders outside it are rejected with a `400` you can map straight onto the form. The `invalid_fields` entry carries the tag `unsupported_ship_to_country` and the field that failed (`shipping_address.country_code` or `requested_lab_address.country_code`), and the problem detail includes the allowed codes:

```json
{
  "detail": "This test isn't available in the provided country. Supported country codes: GB.",
  "status": 400,
  "invalid_fields": [
    {
      "field": "shipping_address.country_code",
      "message": "must be one of: GB",
      "tag": "unsupported_ship_to_country",
      "value": "US"
    }
  ],
  "supported_ship_to_countries": ["GB"]
}
```

### AT\_HOME orders

{% tabs %}
{% tab title="Request" %}

```json
{
  "client_order_reference_id": "TEST-ORDER-001",
  "collection_type": "AT_HOME",
  "recipient": {
    "first_name": "John",
    "last_name": "Tan",
    "email": "john.tan@example.com",
    "phone_number": "+447436503302",
    "date_of_birth": "1995-10-10",
    "gender_at_birth": "male"
  },
  "shipping_address": {
    "address_line_1": "123 High Street",
    "city": "London",
    "administrative_area": "England",
    "country_code": "GB",
    "postal_code": "SW1A 1AA"
  },
  "items": [
    {
      "variant_id": "100011",
      "quantity": 1
    }
  ]
}
```

{% endtab %}

{% tab title="Response (201)" %}

```json
{
  "order_id": "256488482397134848",
  "recipient_id": "256488482397134849",
  "order_items": [
    {
      "order_id": "256488482397134848",
      "order_item_id": "256488482397134851",
      "variant_id": "100011",
      "product_type_id": "1",
      "price_per_item_cents": 3999,
      "quantity": 1,
      "currency": 826,
      "results_status": "results.awaiting_sample"
    }
  ],
  "order_status": "order.payment_processing"
}
```

{% endtab %}
{% endtabs %}

### GO\_TO\_LAB orders

For `GO_TO_LAB`, send the address the end user would like to be near as `requested_lab_address`. Terra uses it as a proxy to route the order to the closest available lab. To let the user pick a specific draw site up front, list nearby locations first (see [Finding nearby lab draw sites](#finding-nearby-lab-draw-sites)):

{% tabs %}
{% tab title="Request" %}

```json
{
  "client_order_reference_id": "TEST-ORDER-002",
  "collection_type": "GO_TO_LAB",
  "recipient": {
    "first_name": "Jane",
    "last_name": "Doe",
    "email": "jane.doe@example.com",
    "phone_number": "+12125550100",
    "date_of_birth": "1990-05-15",
    "gender_at_birth": "female"
  },
  "requested_lab_address": {
    "address_line_1": "350 5th Avenue",
    "city": "New York",
    "administrative_area": "NY",
    "country_code": "US",
    "postal_code": "10118"
  },
  "items": [
    {
      "variant_id": "100011",
      "quantity": 1
    }
  ]
}
```

{% endtab %}

{% tab title="Response (201)" %}

```json
{
  "order_id": "256488482397134852",
  "recipient_id": "256488482397134853",
  "order_items": [
    {
      "order_id": "256488482397134852",
      "order_item_id": "256488482397134855",
      "variant_id": "100011",
      "product_type_id": "1",
      "price_per_item_cents": 3999,
      "quantity": 1,
      "currency": 840,
      "results_status": "results.awaiting_sample"
    }
  ],
  "order_status": "order.payment_processing"
}
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Order responses include a `confirmed_lab_address` field: the nearest draw site to the requested lab address, resolved at order time. It is best-effort - `null` when resolution is unavailable, so don't build a flow that requires it. The requisition is typically accepted at any of the network's sites (see the labs listing below).
{% endhint %}

## Finding nearby lab draw sites

To let your end user choose a convenient location before placing a `GO_TO_LAB` order, list nearby Patient Service Centers for a US zip code:

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/labs?zip_code=10001' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

```json
{
  "labs": [
    {
      "code": "PSC12345",
      "name": "Quest Diagnostics - Midtown",
      "address": {
        "address_line_1": "245 W 35th St",
        "city": "New York",
        "administrative_area": "NY",
        "country_code": "US",
        "postal_code": "10001"
      },
      "phone": "+1-212-555-0100",
      "hours": { "monday": "08:00-17:00" },
      "latitude": 40.7549,
      "longitude": -73.984,
      "scheduling": true,
      "distance": 0.4
    }
  ]
}
```

`distance` is in miles from the requested zip code; `scheduling` indicates whether online scheduling is open at that site.

## Letting the user pick a draw site

To bind a `GO_TO_LAB` order to the site your user chose (instead of the automatic nearest-site resolution), pass the chosen row's `code` and `address.postal_code` as `requested_lab` when creating the order:

```json
{
  "collection_type": "GO_TO_LAB",
  "requested_lab_address": { "...": "the user's search area" },
  "requested_lab": { "code": "PSC12345", "postal_code": "10001-6975" }
}
```

Both values come verbatim from the `GET /labs` row (ZIP+4 is fine - it is normalized server-side). The outcomes:

* **Bound** - the order response (and any later `GET /orders/{id}`) carries `confirmed_lab` (the full site: code, name, address, phone, hours) and `confirmed_lab_address`. Render it as "your draw site".
* **Unknown code** - `400` with an `invalid_fields` entry on `requested_lab.code` tagged `unknown_lab_code`. The site list may have changed: re-fetch `GET /labs` and let the user re-select. Nothing was created, so retrying is safe.
* **Lookup temporarily unavailable** - the order is **accepted unbound** (`confirmed_lab` is `null`). The requisition is typically valid at any of the network's sites, so a brief outage never fails an order. `GET /orders/{id}` echoes your `requested_lab` so you can tell this case apart from "no selection was made".

Without `requested_lab`, Terra falls back to resolving the nearest site to `requested_lab_address` (best-effort).


# Webhooks

How Vantage API delivers order and result updates to your endpoint: event families and payloads, HMAC signature verification, and retry semantics.

## Overview

Webhooks are how Vantage API keeps you connected to the kit throughout the fulfilment and results process. Every state change is delivered as a signed HTTP `POST` to the HTTPS endpoint you registered ([Account setup](/vantage-api/account-setup-and-api-keys#configure-your-webhook-endpoint)).

There are **two event families**, distinguished by the `event_type` field:

| `event_type`                       | Scope      | What it carries                                                                                                   |
| ---------------------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------- |
| `order.status_changed`             | Order      | Fulfilment progress: a `status` in the same `order.*` vocabulary REST uses, plus `tracking_number` once available |
| `order_item.results_status_change` | Order item | Results progress: a `results_status` in the `results.*` vocabulary, plus the `test_taker`                         |

{% hint style="info" %}
`event_type` tells you **which family** the event belongs to; the `status` / `results_status` field inside `data` tells you **which state** was reached. Route on `event_type`, then switch on the status field.
{% endhint %}

Every payload has the same envelope:

```json
{
  "event_type": "order.status_changed",
  "event_id": "249956485092777984",
  "timestamp": 1763661470,
  "data": { }
}
```

* `event_id` - unique per event, serialized as a JSON **string** (like all Vantage IDs). Delivery is **at-least-once**: deduplicate on `event_id`. It equals the `X-Terra-Trace-Id` header.
* `timestamp` - Unix **seconds** when this delivery was built. It can differ between retries of the same event; use `X-Terra-Ordering-Timestamp` to order events.

## Headers

| Header                       | Description                                                                                               | Example                     |
| ---------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------- |
| `X-Terra-Signature`          | HMAC signature with timestamp                                                                             | `t=1763661470,v1=a1b2c3...` |
| `X-Terra-Trace-Id`           | Unique ID for debugging (matches the `event_id`)                                                          | `249956485092777984`        |
| `Content-Type`               | Always `application/json`                                                                                 | `application/json`          |
| `X-Terra-Version`            | The API version the payload was rendered in. See [Versioning](/vantage-api/versioning)                    | `2026-10-01`                |
| `X-Terra-Ordering-Timestamp` | Unix **milliseconds** when the event happened. The same on every retry of the event; omitted when unknown | `1763661470123`             |

## Signature verification

Each Vantage webhook has its own signing secret. Copy it from your Vantage webhook settings in the Terra dashboard, or read it with `GET /environments/{dev_id}/vantage/webhook/secrets` in the [admin API](https://docs.tryterra.co/reference/admin-api/webhook-signing-secrets#vantage-webhooks). Webhooks are signed with **HMAC-SHA256** using that secret. Verify every delivery before trusting it.

The `X-Terra-Signature` header has the format:

```
t=<unix_timestamp_seconds>,v1=<hex_signature>
```

* `t` - Unix timestamp in **seconds** when the webhook was sent
* `v1` - hex-encoded `HMAC-SHA256(signing_secret, "<t>.<raw_body>")`

Verification steps:

1. Parse `t` and `v1` from the header.
2. Reject if `t` is outside your tolerance window of now (5 minutes is a sensible default).
3. Concatenate `<t>` + `.` + the **raw, unaltered request body**.
4. Compute HMAC-SHA256 over that string with your signing secret.
5. Compare to `v1` with a constant-time comparison.

{% tabs %}
{% tab title="Python" %}

```python
import hashlib
import hmac
import time

from flask import Flask, abort, request

app = Flask(__name__)

SIGNING_SECRET = "your_signing_secret_here"
TIMESTAMP_TOLERANCE = 300  # 5 minutes, in seconds


def verify_webhook(request):
    signature_header = request.headers.get("X-Terra-Signature")
    if not signature_header:
        return False, "Missing signature header"

    try:
        parts = dict(
            item.split("=", 1)
            for item in signature_header.split(",")
            if "=" in item
        )
        timestamp = int(parts["t"])
        received_signature = parts["v1"]
    except (KeyError, ValueError):
        return False, "Invalid signature format"

    if abs(int(time.time()) - timestamp) > TIMESTAMP_TOLERANCE:
        return False, "Timestamp too old or in future"

    body = request.get_data(as_text=True)
    signed_string = f"{timestamp}.{body}"

    expected_signature = hmac.new(
        SIGNING_SECRET.encode("utf-8"),
        signed_string.encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(expected_signature, received_signature):
        return False, "Signature mismatch"

    return True, None


@app.route("/webhooks/terra", methods=["POST"])
def webhook_handler():
    valid, error = verify_webhook(request)
    if not valid:
        abort(401, description=error)

    data = request.get_json()
    print(f"Received webhook: {data}")

    return "", 200


if __name__ == "__main__":
    app.run(port=3000)
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

const timestampTolerance = 300 // 5 minutes, in seconds

func VerifyWebhook(r *http.Request, signingSecret string) (bool, error) {
	bodyBytes, err := io.ReadAll(r.Body)
	if err != nil {
		return false, fmt.Errorf("failed to read body: %w", err)
	}
	defer r.Body.Close()

	signatureHeader := r.Header.Get("X-Terra-Signature")
	if signatureHeader == "" {
		return false, fmt.Errorf("missing X-Terra-Signature header")
	}

	var timestamp int64
	var receivedSig string
	for _, part := range strings.Split(signatureHeader, ",") {
		keyValue := strings.SplitN(part, "=", 2)
		if len(keyValue) != 2 {
			continue
		}
		switch keyValue[0] {
		case "t":
			timestamp, err = strconv.ParseInt(keyValue[1], 10, 64)
			if err != nil {
				return false, fmt.Errorf("invalid timestamp: %w", err)
			}
		case "v1":
			receivedSig = keyValue[1]
		}
	}

	age := time.Now().Unix() - timestamp
	if age > timestampTolerance || age < -timestampTolerance {
		return false, fmt.Errorf("timestamp too old or in future")
	}

	signedString := fmt.Sprintf("%d.%s", timestamp, string(bodyBytes))

	mac := hmac.New(sha256.New, []byte(signingSecret))
	mac.Write([]byte(signedString))
	expectedSig := hex.EncodeToString(mac.Sum(nil))

	if subtle.ConstantTimeCompare([]byte(expectedSig), []byte(receivedSig)) != 1 {
		return false, fmt.Errorf("signature mismatch")
	}
	return true, nil
}

func WebhookHandler(w http.ResponseWriter, r *http.Request) {
	signingSecret := os.Getenv("TERRA_SIGNING_SECRET")

	valid, err := VerifyWebhook(r, signingSecret)
	if err != nil || !valid {
		http.Error(w, "Invalid signature", http.StatusUnauthorized)
		return
	}

	w.WriteHeader(http.StatusOK)
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Compute the HMAC over the **raw request body bytes**, before any JSON parsing or re-serialization - re-encoding the JSON can reorder keys and change whitespace, which breaks the signature.
{% endhint %}

## Delivery and retries

* Respond with any **2xx** status quickly (within 10 seconds); do heavy processing asynchronously.
* On failure (network error, timeout, `408`, `429`, or any `5xx`), the first delivery makes up to **5 HTTP attempts** with exponential backoff and jitter (roughly 1s, 2s, 4s, 8s). If they all fail, the event is re-queued and redelivered as **single attempts with growing delays** (starting at 5s, doubling up to a 10-minute cap), up to 10 deliveries in total - at most \~14 calls spread over \~30 minutes - before the event is parked. Make your handler idempotent either way. Other `4xx` responses are treated as a rejection and are **not** retried.
* Parked (dead-lettered) events can be replayed by Terra - they are not silently lost.
* Every event is recorded when it happens, together with the change that caused it. If it cannot be sent straight away, Terra sends it later under the same `event_id`, so an event is never lost because a send failed.
* Delivery is **at-least-once** and ordering is not guaranteed: an event sent later can arrive after a newer one for the same order. Deduplicate on `event_id`, and when two events for the same order arrive out of order, the one with the higher `X-Terra-Ordering-Timestamp` is newer. Treat each event's status as the authoritative current state rather than assuming you saw every intermediate step.

Each event has a delivery status and a record of every HTTP attempt: when it was made, the URL, the status code your endpoint returned (or why there was none) and how long it took. See them in the dashboard under Vantage → Event log, or list delivery outcomes with `GET /api/v1/webhook-deliveries` - see [Monitoring and debugging](/vantage-api/monitoring).

## Event reference

### `order.status_changed`

`data` fields: `order_id` (string), `status`, plus `tracking_number` and (sandbox only) `supplier_item_id` once available.

| `status`                   | Meaning                                                 |
| -------------------------- | ------------------------------------------------------- |
| `order.payment_processing` | Payment being processed. Sent when the order is created |
| `order.payment_complete`   | Payment confirmed                                       |
| `order.payment_failed`     | Payment failed                                          |
| `order.processing`         | Order accepted and being prepared by the supplier       |
| `order.delayed`            | Fulfilment delayed                                      |
| `order.delivery_fulfilled` | Delivery details available - carries `tracking_number`  |
| `order.completed`          | Order complete                                          |
| `order.cancelled`          | Order cancelled                                         |

Example:

```json
{
  "event_type": "order.status_changed",
  "event_id": "249956485092777984",
  "timestamp": 1763661470,
  "data": {
    "order_id": "251285377984405504",
    "status": "order.delivery_fulfilled",
    "tracking_number": "KnD3d5PMZyq5ulNcWkrq"
  }
}
```

{% hint style="info" %}
REST reads of the same order use the identical vocabulary - a webhook `status` can be matched verbatim against `order_status` or `status_history`.
{% endhint %}

### `order_item.results_status_change`

`data` fields: `order_id`, `order_item_id`, `variant_id` (all strings), `results_status`, and a `test_taker` object (`test_taker_id` string, `first_name`, `last_name`, `email`, `phone_number` E.164 string). Depending on the status, also: `failure_cause`, `escalation_level`, `acknowledgment_due_by`.

| `results_status`                   | Meaning                                                                       | Extra fields                                  |
| ---------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------- |
| `results.kit_activated`            | End user activated their kit (variants with `requires_activation: true` only) | -                                             |
| `results.sample_processing_in_lab` | Lab confirmed receipt of the sample                                           | -                                             |
| `results.partial_results_ready`    | A subset of the panel has resulted                                            | -                                             |
| `results.results_ready`            | Results available - fetch and acknowledge                                     | -                                             |
| `results.sample_rejected`          | Lab rejected the sample                                                       | `failure_cause` (e.g. `"blood contaminated"`) |
| `results.lab_processing_error`     | Lab could not process the sample                                              | -                                             |
| `results.escalation_raised`        | Clinical escalation on the result set                                         | `escalation_level`, `acknowledgment_due_by`   |

(`results.awaiting_sample` is the initial per-item state set at order creation; it appears in the order response rather than as a webhook.)

Example - results ready:

```json
{
  "event_type": "order_item.results_status_change",
  "event_id": "249958796259139584",
  "timestamp": 1763662021,
  "data": {
    "order_id": "251285377984405504",
    "order_item_id": "251285377984405507",
    "variant_id": "100041",
    "results_status": "results.results_ready",
    "test_taker": {
      "test_taker_id": "257837964552478720",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone_number": "+14155551234"
    }
  }
}
```

Example - escalation raised:

```json
{
  "event_type": "order_item.results_status_change",
  "event_id": "252476147693166592",
  "timestamp": 1764262204,
  "data": {
    "order_id": "251285377984405504",
    "order_item_id": "251285377984405507",
    "variant_id": "100041",
    "results_status": "results.escalation_raised",
    "escalation_level": "medium",
    "acknowledgment_due_by": "2026-07-24T16:04:01Z",
    "test_taker": {
      "test_taker_id": "257837964552478720",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone_number": "+14155551234"
    }
  }
}
```

`escalation_level` is one of `not_escalated`, `very_low`, `low`, `medium`, `high`, `very_high`. Escalations require prompt acknowledgment - see [Acknowledging Results](/vantage-api/acknowledging-results).


# Results

Fetching test results as FHIR documents: the download flow, how to read the Bundle structure, out-of-range and critical values, and failure scenarios.

## Fetching results

When an order item reaches `results.results_ready` (via webhook), fetch the result:

```
GET /api/v1/results/{order_item_id}?test_taker_id={test_taker_id}
```

Both identifiers are **required**. `test_taker_id` arrives on every result webhook (and is recoverable from `GET /api/v1/orders/{orderID}` under `items[].test_taker_ids`).

```json
{
  "download_url": "https://storage.googleapis.com/.../normalised.json?X-Goog-Signature=...",
  "format": "json",
  "expires_at": "2025-11-19T19:08:04.400Z"
}
```

The presigned `download_url` is valid for **15 minutes**. Re-call the endpoint to mint a fresh URL rather than caching it. Each order item holds at most one panel, so a result is uniquely identified by its `order_item_id`.

To find results across your account (e.g. ready but unacknowledged), use the `GET /api/v1/results` index - see [Managing orders](/vantage-api/managing-orders#list-results).

## Reading the FHIR document

The download is a [FHIR](https://hl7.org/fhir/) **Bundle** (JSON) containing three resource types:

* **`DiagnosticReport`** - the panel: which observations it contains (`result` references), when it was collected (`effectiveDateTime`) and issued, and the `subject` patient.
* **`Patient`** - the test taker's demographics as registered at activation.
* **`Observation`** - one per biomarker: the `code` (test identifier and display name), `valueQuantity` (numeric value + unit), `referenceRange` (normal bounds), and `interpretation` (HL7 coding).

You mostly iterate the Bundle's `entry` array, pick out the `Observation` resources, and read value, unit, range, and interpretation from each.

### Out-of-range results

Compare `valueQuantity.value` against `referenceRange`. In the example below, HDL Cholesterol is below normal, which you can observe from:

* `low`: 40.0, `high`: 100.0
* `value`: 35.2
* `interpretation` code `L` ("Below low normal")

Interpretation codes follow [HL7 table 0078](https://hl7-definition.caristix.com/v2/HL7v2.8/Tables/0078): `N` normal, `L` below low normal, `H` above high normal, with `LL` / `HH` marking critical values.

### Critical results - must be handled properly

Depending on the test supplier you may receive a `results.escalation_raised` webhook indicating the overall severity of the result set, with an `escalation_level` of `not_escalated`, `very_low`, `low`, `medium`, `high`, or `very_high`, and an `acknowledgment_due_by` deadline. In critical cases the `interpretation` field will typically carry `HH` or `LL` codes.

Escalated results demand prompt review and acknowledgment - see [Acknowledging Results](/vantage-api/acknowledging-results) and [Webhooks](/vantage-api/webhooks#order_itemresults_status_change).

### Failed tests

* `results.sample_rejected` webhooks carry a `failure_cause` (e.g. contamination) when the lab rejects a sample.
* `results.lab_processing_error` indicates the lab could not process the sample.

In either case there will be no result document to fetch for that item; handle these paths in your product flow (e.g. offer a replacement kit).

### Example result document

```json
{
  "resourceType": "Bundle",
  "type": "collection",
  "timestamp": "2026-07-20T15:29:24+00:00",
  "entry": [
    {
      "fullUrl": "DiagnosticReport/dr-252463239248650243",
      "resource": {
        "resourceType": "DiagnosticReport",
        "id": "dr-252463239248650243",
        "code": { "text": "Laboratory Panel" },
        "status": "final",
        "effectiveDateTime": "2026-07-20T15:29:23+00:00",
        "issued": "2026-07-20T15:29:24+00:00",
        "subject": { "reference": "Patient/252463822202380289" },
        "result": [
          { "display": "Total Cholesterol", "reference": "Observation/obs-252463239248650243-CHOL" },
          { "display": "HDL Cholesterol", "reference": "Observation/obs-252463239248650243-HDL" },
          { "display": "Hemoglobin A1c", "reference": "Observation/obs-252463239248650243-HBA1C" }
        ]
      }
    },
    {
      "fullUrl": "Patient/252463822202380289",
      "resource": {
        "resourceType": "Patient",
        "id": "252463822202380289",
        "name": [{ "family": "Doe", "given": ["John"] }],
        "gender": "male",
        "birthDate": "1970-01-01",
        "address": [
          {
            "line": ["123 Test Street", "Apt 4B"],
            "city": "San Francisco",
            "state": "CA",
            "postalCode": "94102",
            "country": "US"
          }
        ],
        "telecom": [
          { "system": "email", "value": "john.doe@example.com" },
          { "system": "phone", "value": "+14155551234" }
        ]
      }
    },
    {
      "fullUrl": "Observation/obs-252463239248650243-HDL",
      "resource": {
        "resourceType": "Observation",
        "id": "obs-252463239248650243-HDL",
        "status": "final",
        "code": {
          "coding": [{ "code": "HDL", "display": "HDL Cholesterol" }],
          "text": "HDL Cholesterol"
        },
        "subject": { "reference": "Patient/252463822202380289" },
        "effectiveDateTime": "2026-07-20T15:29:23+00:00",
        "issued": "2026-07-20T15:29:24+00:00",
        "valueQuantity": { "value": 35.2, "unit": "mg/dL", "code": "mg/dL" },
        "referenceRange": [
          { "low": { "value": 40 }, "high": { "value": 100 }, "text": "40.0 - 100.0" }
        ],
        "interpretation": [
          {
            "coding": [
              {
                "code": "L",
                "display": "Below low normal",
                "system": "http://terminology.hl7.org/CodeSystem/v2-0078"
              }
            ]
          }
        ]
      }
    },
    {
      "fullUrl": "Observation/obs-252463239248650243-HBA1C",
      "resource": {
        "resourceType": "Observation",
        "id": "obs-252463239248650243-HBA1C",
        "status": "final",
        "code": {
          "coding": [{ "code": "HBA1C", "display": "Hemoglobin A1c" }],
          "text": "Hemoglobin A1c"
        },
        "subject": { "reference": "Patient/252463822202380289" },
        "effectiveDateTime": "2026-07-20T15:29:23+00:00",
        "issued": "2026-07-20T15:29:24+00:00",
        "valueQuantity": { "value": 5.2, "unit": "%", "code": "%" },
        "referenceRange": [
          { "low": { "value": 4 }, "high": { "value": 5.6 }, "text": "4.0 - 5.6" }
        ],
        "interpretation": [
          {
            "coding": [
              {
                "code": "N",
                "display": "Normal",
                "system": "http://terminology.hl7.org/CodeSystem/v2-0078"
              }
            ]
          }
        ]
      }
    }
  ]
}
```


# Acknowledging results

Result acknowledgment is a mandatory compliance step: patients cannot access their results until you acknowledge them, and failing to acknowledge transfers liability to your organisation.

## Overview

Acknowledging results is not optional - it is a fundamental requirement in the patient care workflow. This acknowledgment serves as documentation that clients have reviewed test outcomes and take responsibility for communicating appropriate severity levels to their end users.

All results, whether indicating ***low** to **high** clinical escalation*, must be explicitly acknowledged within the system before patients can access their results. This mandatory acknowledgment protects patients by ensuring they receive informed guidance about their test outcomes and any necessary next steps.

{% hint style="danger" %}
Failure to acknowledge results initiates a chain of liability that transfers responsibility directly to you, and your organisation assumes full liability for any adverse outcomes resulting from delayed or unacknowledged results.
{% endhint %}

{% hint style="warning" %}
If results remain unacknowledged, test suppliers and medical teams are authorised to **reach out directly** to patients to ensure they receive critical health information. Escalated results carry an explicit `acknowledgment_due_by` deadline in the webhook payload.
{% endhint %}

## Acknowledgment must be an explicit user action

The acknowledge call records the end user's affirmative confirmation that they have received and viewed their results. It must be triggered by an explicit end-user action - a button or checkbox in your UI after the results are displayed - **never automatically** by your backend on retrieval or delivery. Build the flow as: fetch the result → present it to the user → the user confirms → your backend calls the acknowledge endpoint.

### Example acknowledgement page

* **N.B.** The test taker cannot see results until acknowledging.

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-55be0dbbe08bd4146e72c7f3cd2a20ae1f02f1a7%2Fvantage-acknowledging-results.png?alt=media" alt="Example acknowledgement page shown to the end user"><figcaption></figcaption></figure>

## Acknowledgement endpoint

```
POST /api/v1/results/{order_item_id}/acknowledge?test_taker_id={test_taker_id}
```

Both `order_item_id` (path) and `test_taker_id` (query) are **required**. The `test_taker_id` arrives on every result webhook, or via `GET /api/v1/orders/{orderID}` under `items[].test_taker_ids`.

{% tabs %}
{% tab title="cURL" %}

```bash
curl --request POST \
  'https://vantage-sandbox.tryterra.co/api/v1/results/251285377984405507/acknowledge?test_taker_id=257837964552478720' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

order_item_id = "251285377984405507"
test_taker_id = "257837964552478720"
url = f"https://vantage-sandbox.tryterra.co/api/v1/results/{order_item_id}/acknowledge"

response = requests.post(
    url,
    auth=("YOUR_DEV_ID", "YOUR_API_KEY"),
    params={"test_taker_id": test_taker_id},
)
print(response.json())
print(response.status_code)
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	orderItemID := "251285377984405507"
	testTakerID := "257837964552478720"
	url := fmt.Sprintf(
		"https://vantage-sandbox.tryterra.co/api/v1/results/%s/acknowledge?test_taker_id=%s",
		orderItemID, testTakerID,
	)

	req, err := http.NewRequest("POST", url, nil)
	if err != nil {
		panic(err)
	}
	req.SetBasicAuth("YOUR_DEV_ID", "YOUR_API_KEY")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="200" %}

```json
{ "status": "acknowledged" }
```

{% endtab %}
{% endtabs %}

To find results that are ready but not yet acknowledged, list `GET /api/v1/results` and filter on `is_acknowledged: false` - see [Managing orders](/vantage-api/managing-orders#list-results).


# Rich text

The rich text document Vantage uses for product descriptions: its node types, fields and the rules for parsing it so new node types never break you.

From API version [`2026-10-29`](/vantage-api/changelog), a product's `description` is a rich text document rather than a string. It is a JSON tree with a node for every Markdown construct: CommonMark (without raw HTML), plus GitHub Flavored Markdown tables, strikethrough and task lists. You get structure you can walk, rather than Markdown or HTML to parse.

Versions before `2026-10-29` serve the same description as plain text.

## Example

```json
{
  "type": "root",
  "children": [
    {
      "type": "heading",
      "level": 2,
      "children": [
        { "type": "text", "value": "What it measures", "bold": false, "italic": false, "strikethrough": false, "code": false }
      ]
    },
    {
      "type": "paragraph",
      "children": [
        { "type": "text", "value": "17 biomarkers", "bold": true, "italic": false, "strikethrough": false, "code": false },
        { "type": "text", "value": " from one finger-prick. ", "bold": false, "italic": false, "strikethrough": false, "code": false },
        {
          "type": "link",
          "url": "https://example.com/biomarkers",
          "title": null,
          "children": [
            { "type": "text", "value": "See the list", "bold": false, "italic": false, "strikethrough": false, "code": false }
          ]
        }
      ]
    },
    {
      "type": "list",
      "list_type": "unordered",
      "start": null,
      "children": [
        {
          "type": "list_item",
          "checked": null,
          "children": [
            {
              "type": "paragraph",
              "children": [
                { "type": "text", "value": "Cholesterol", "bold": false, "italic": false, "strikethrough": false, "code": false }
              ]
            }
          ]
        }
      ]
    }
  ]
}
```

A product with no description has `{ "type": "root", "children": [] }`.

## The model

Every node has a `type`. Every field a node type lists below is always present. A field with no value is `null`, never omitted.

The document is a `root` node whose `children` are **blocks**. Blocks hold either more blocks or **inline** nodes.

### Blocks

| `type`           | Fields                                                                                                                                                                                     | Notes                                                                                                                |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| `paragraph`      | `children`: inline nodes                                                                                                                                                                   | Empty `children` is an empty paragraph.                                                                              |
| `heading`        | <p><code>level</code>: 1 to 6<br><code>children</code>: inline nodes</p>                                                                                                                   | 1 is the most prominent, as Markdown's `#` to `######`.                                                              |
| `blockquote`     | `children`: blocks                                                                                                                                                                         |                                                                                                                      |
| `list`           | <p><code>list\_type</code>: <code>ordered</code> or <code>unordered</code><br><code>start</code>: integer or <code>null</code><br><code>children</code>: <code>list\_item</code> nodes</p> | `start` is the first item's number in an ordered list, and `null` in an unordered one. A list has at least one item. |
| `list_item`      | <p><code>checked</code>: boolean or <code>null</code><br><code>children</code>: blocks</p>                                                                                                 | `checked` is set for a task list item, and `null` otherwise. A nested list is a `list` among the item's blocks.      |
| `code_block`     | <p><code>language</code>: string or <code>null</code><br><code>value</code>: string</p>                                                                                                    | `value` is the code verbatim.                                                                                        |
| `thematic_break` | none                                                                                                                                                                                       | A horizontal rule.                                                                                                   |
| `table`          | <p><code>align</code>: one entry per column: <code>left</code>, <code>center</code>, <code>right</code> or <code>null</code><br><code>children</code>: <code>table\_row</code> nodes</p>   | The first row is the header row. Every row has one cell per column.                                                  |
| `table_row`      | <p><code>header</code>: boolean<br><code>children</code>: <code>table\_cell</code> nodes</p>                                                                                               | `header` is `true` on the first row only.                                                                            |
| `table_cell`     | `children`: inline nodes                                                                                                                                                                   |                                                                                                                      |

### Inline nodes

| `type`       | Fields                                                                                                                               | Notes                                                                                                                                 |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `text`       | <p><code>value</code>: string<br><code>bold</code>, <code>italic</code>, <code>strikethrough</code>, <code>code</code>: booleans</p> | A run of characters sharing one set of styles. `code` is inline code. A `\n` in `value` is a soft line break. `value` is never empty. |
| `link`       | <p><code>url</code>: string<br><code>title</code>: string or <code>null</code><br><code>children</code>: inline nodes</p>            | `url` is an `https`, `http` or `mailto` URL. A link never contains another link.                                                      |
| `image`      | <p><code>url</code>: string<br><code>alt</code>: string<br><code>title</code>: string or <code>null</code></p>                       | `url` is an `https` URL. `alt` is empty for a decorative image.                                                                       |
| `line_break` | none                                                                                                                                 | A hard line break.                                                                                                                    |

## Handling future additions

We'll add to this format over time, for example new node types such as block-level images, or new text styles. These additions don't come with a new API version, so make sure your code copes with things it hasn't seen before:

* If a node has a field you don't know, ignore it.
* If you come across a node `type` you don't know, skip it. If it has `children`, you can show those instead.
* If `list_type` has a value you don't know, treat the list as unordered. If an `align` value is unknown, use the default alignment.

Changes that could break existing code, such as removing or renaming a field or node type, only happen in a new API version. See [Versioning](/vantage-api/versioning).

This TypeScript example turns a description into plain text, skipping anything it doesn't recognise:

```typescript
type Node = { type: string; children?: Node[]; [field: string]: unknown };

function plainText(node: Node): string {
  switch (node.type) {
    case "text":
      return node.value as string;
    case "line_break":
      return "\n";
    case "image":
      return node.alt as string;
    case "code_block":
      return node.value as string;
    case "root":
    case "blockquote":
      return (node.children ?? []).map(plainText).join("\n\n");
    case "list":
    case "list_item":
    case "table":
    case "table_row":
      return (node.children ?? []).map(plainText).join("\n");
    default:
      return (node.children ?? []).map(plainText).join("");
  }
}
```

The full schema of every node is in the [API reference](https://docs.tryterra.co/reference/vantage-api).


# Errors

The error format Vantage API uses (RFC 7807 problem details), what each HTTP status code means, and how to handle validation failures.

## Error format

All error responses follow the [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807) problem-detail format:

```json
{
  "type": "https://docs.tryterra.co/errors/not-found-error",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "resource not found",
  "instance": "/api/v1/orders"
}
```

| Field      | Meaning                                       |
| ---------- | --------------------------------------------- |
| `type`     | A URI identifying the error category          |
| `title`    | Short human-readable summary                  |
| `status`   | The HTTP status code, repeated in the body    |
| `detail`   | Human-readable explanation of this occurrence |
| `instance` | The request path that produced the error      |

## Credential refusals

Most requests refused for their credentials get `Content-Type: application/problem+json` and a `code`, whatever the API version. A few, such as a scope that one operation checks for itself, keep the format above, so choose the schema by `Content-Type`.

```json
{
  "type": "about:blank",
  "title": "unauthorized",
  "instance": "/api/v1/orders?limit=10",
  "detail": "The credential is missing, invalid, expired or revoked.",
  "code": "unauthorized"
}
```

| `code`                      | Status | Meaning                                                  |
| --------------------------- | ------ | -------------------------------------------------------- |
| `unauthorized`              | `401`  | The key or token is missing, invalid, expired or revoked |
| `scope_missing`             | `403`  | The token lacks the scope this operation needs           |
| `audience_restricted`       | `403`  | The token is not granted for this `dev-id`               |
| `authorization_unavailable` | `503`  | The credential could not be checked; retry with backoff  |

The status is not repeated in the body.

## Status codes

| Status | When you'll see it                                                                                                                                                                                                                                                                  |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | Malformed request: invalid JSON, missing required fields or query parameters (e.g. `test_taker_id`), invalid IDs or pagination parameters                                                                                                                                           |
| `401`  | Missing or invalid credentials - check your `dev-id` / API key and the auth scheme ([Account setup](/vantage-api/account-setup-and-api-keys#authentication))                                                                                                                        |
| `403`  | Credentials are valid but the action is not allowed: suspended account, account without Vantage access, ordering a product disabled in your catalog or not sold in your environment's [markets](/vantage-api/core-concepts#markets), or calling the simulate endpoint in production |
| `404`  | Resource not found - includes orders that exist but do not belong to you                                                                                                                                                                                                            |
| `409`  | Conflict - e.g. activating a kit that is already activated                                                                                                                                                                                                                          |
| `422`  | Semantically invalid - e.g. a simulate event that is not a valid transition from the current status                                                                                                                                                                                 |
| `500`  | Something went wrong on Terra's side - retry with backoff, and contact support if it persists                                                                                                                                                                                       |
| `503`  | An upstream supplier service is temporarily unavailable - retry with backoff                                                                                                                                                                                                        |

### Payment and idempotency errors

* `402` - the payment could not be authorized when creating an order. Nothing was created and nothing was charged; it is safe to retry (e.g. after the end user updates their payment details).
* `409` - an `Idempotency-Key` you already used was sent with a different request body. Generate a fresh key for a genuinely new order.

## Validation errors on order creation

`POST /api/v1/orders` returns a problem-detail body extended with a per-field breakdown:

```json
{
  "type": "https://api.terra-diagnostics.com/errors/validation-error",
  "title": "Validation Failed",
  "status": 400,
  "detail": "One or more required fields are missing or invalid",
  "instance": "/api/v1/orders",
  "invalid_fields": [
    {
      "field": "PhoneNumber",
      "message": "PhoneNumber is not a valid phone number for the provided country code",
      "tag": "phone_with_country",
      "value": "1234567890"
    }
  ]
}
```

Surface `invalid_fields[].message` to fix the request; each entry names the offending field, the failed validation rule (`tag`), and the rejected value.

## Handling errors well

* **Retry `5xx` and `503` with exponential backoff**; do not retry `4xx` (fix the request instead).
* **Retry `POST /api/v1/orders` safely with an `Idempotency-Key` header.** Send a unique key per order attempt (a UUID is fine); retrying with the same key and the same body returns the original result instead of creating a second order or charge. The same key with a *different* body returns `409`. Without the header, creation is not deduplicated - fall back to checking `GET /api/v1/orders` for your `client_order_reference_id` before retrying (see [Best practices](/vantage-api/best-practices)).
* On `401`/`403`, verify which environment you are calling: sandbox and production access are enabled separately ([Account setup](/vantage-api/account-setup-and-api-keys)).


# Monitoring and debugging

Observe your integration in production: the analytics overview endpoint, webhook events and their delivery attempts, delivery outcomes, and how to debug missed webhooks.

## Analytics overview

`GET /api/v1/overview` returns a summary of your account's activity for a time window (default: the last 7 days):

```bash
curl 'https://vantage.tryterra.co/api/v1/overview?since=2026-07-01T00:00:00Z' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

```json
{
  "orders": {
    "total": 37,
    "by_status": {
      "order.completed": 29,
      "order.processing": 8
    }
  },
  "results": {
    "total": 25,
    "missing": 4
  },
  "webhooks": {
    "failed_total": 2,
    "daily": [
      { "date": "2026-07-18", "failed": 1 },
      { "date": "2026-07-19", "failed": 1 }
    ]
  }
}
```

* `orders.by_status` is keyed by the current `order.*` fulfilment status.
* `results.missing` counts delivered/completed orders still waiting on results - drill into them with `GET /api/v1/orders?missing=true` ([Managing orders](/vantage-api/managing-orders#list-orders)).
* `webhooks.failed_total` > 0 means deliveries to your endpoint are failing - investigate below.

## Webhook events and delivery attempts

Every webhook event is recorded the moment it happens, with a delivery status and a record of each HTTP attempt to your endpoint. In the dashboard, **Vantage → Event log** lists your events, including ones Terra has not delivered yet:

| Status      | Meaning                                                                                                     |
| ----------- | ----------------------------------------------------------------------------------------------------------- |
| `pending`   | Not delivered yet: no attempt has been made, or the last one failed and Terra will retry at the time shown  |
| `delivered` | Your endpoint returned 2xx                                                                                  |
| `failed`    | Terra stopped trying: a response it does not retry, a URL that can never be delivered to, or the last retry |
| `canceled`  | Never sent, for example because no webhook URL or signing secret was set; the event says why                |

Open an event to see its payload and every attempt: when it was made, the URL, the status code your endpoint returned (or why there was none, such as `host_not_found` or `connection_failed`) and how long it took. To send a delivered event again, use `POST /api/v1/webhook-events/resend`. You can also ask your AI assistant, for example "Which Vantage webhooks failed this week, and why?" - see [Use Vantage from your AI assistant](/vantage-api/overview#use-vantage-from-your-ai-assistant).

## Webhook delivery outcomes

`GET /api/v1/webhook-deliveries` lists the outcome of every event whose delivery has finished, newest first (keyset-paginated). Events still being retried are not listed until they finish.

```bash
curl 'https://vantage.tryterra.co/api/v1/webhook-deliveries?outcome=failed' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY'
```

```json
{
  "data": [
    {
      "event_id": "333410942627700737",
      "event_type": "order_item.results_status_change",
      "order_id": "333410942627700736",
      "order_item_id": "333410942627700737",
      "outcome": "rejected",
      "final_status_code": 401,
      "attempts": 1,
      "completed_at": "2026-07-19T10:41:22Z",
      "event_created_at": "2026-07-19T10:39:03Z"
    },
    {
      "event_id": "333410942627700912",
      "event_type": "order.status_changed",
      "order_id": "333410942627700900",
      "order_item_id": "",
      "outcome": "dead_lettered",
      "final_status_code": null,
      "attempts": 14,
      "completed_at": "2026-07-19T11:02:47Z",
      "event_created_at": "2026-07-19T10:20:11Z"
    }
  ],
  "has_more": false,
  "next_cursor": null
}
```

| `outcome`       | Meaning                                                                                            |
| --------------- | -------------------------------------------------------------------------------------------------- |
| `delivered`     | Your endpoint returned 2xx                                                                         |
| `rejected`      | Your endpoint returned a non-retryable 4xx - the event was not retried                             |
| `invalid`       | The webhook URL can never be delivered to, for example because it is not a valid http or https URL |
| `dead_lettered` | All retries exhausted - the event is parked and can be replayed by Terra                           |
| `replayed`      | A previously failed event was re-delivered                                                         |

Filter with `outcome=<value>`, or `outcome=failed` as a shorthand for `rejected|invalid|dead_lettered`.

* `event_type` uses the same strings as the webhook payloads (`order.status_changed`, `order_item.results_status_change`).
* `attempts` counts every HTTP attempt made for the event, across all retries.
* `final_status_code` is the status code your endpoint returned to the last attempt, or `null` when that attempt got no HTTP response (a DNS failure, refused connection or timeout).

## Debugging a missed webhook

1. **Check the event in the dashboard** - Vantage → Event log shows whether it is still `pending` and what each attempt got back. `GET /api/v1/webhook-deliveries` lists finished deliveries. `rejected` means your endpoint returned an error; `invalid` means the registered URL can never be delivered to; `dead_lettered` means your endpoint was unreachable through all retries.
2. **Cross-check current state via REST** - `GET /api/v1/orders/{orderID}` shows the authoritative `status_history` regardless of what was delivered.
3. **Verify your registered URL** - `GET /api/v1/clients/webhook-url` for the environment in question (sandbox and production hold separate URLs).
4. **Check your signature verification** - a verifier that rejects valid signatures shows up as `rejected` with a `final_status_code` of 401. Common causes: verifying against a re-serialized body instead of the raw bytes, or treating the timestamp as milliseconds (it is Unix **seconds**). See [Webhooks](/vantage-api/webhooks#signature-verification).
5. **Contact support with the `event_id`** (or the `X-Terra-Trace-Id` header value from a delivery) - it uniquely identifies the delivery for Terra's team, and dead-lettered events can be replayed.


# Best practices

Patterns that keep a Vantage integration robust: webhook handling, deduplication, safe retries, ID handling, and result delivery done right.

## Webhook handling

* **Verify the signature on every delivery** before parsing the body ([Webhooks](/vantage-api/webhooks#signature-verification)). Use the raw request bytes and remember the timestamp is Unix **seconds**.
* **Return 2xx fast.** Persist the event and process asynchronously; Terra times out deliveries after 10 seconds and treats non-2xx as failure.
* **Deduplicate on `event_id`.** Delivery is at-least-once; you will occasionally see the same event twice.
* **Don't assume ordering.** A delivery can be stale by the time it arrives - never let an older status overwrite a newer one you've already recorded. When you must establish the authoritative current state, read `status_history` from `GET /api/v1/orders/{orderID}`.
* **Reconcile periodically.** A daily sweep of `GET /api/v1/orders?missing=true` (delivered orders still waiting on results) and `GET /api/v1/results?status=results.results_ready` (ready but perhaps unacknowledged) catches anything a missed webhook would otherwise hide.

## Placing orders

* **Generate a unique `client_order_reference_id` per order** and store the mapping to `order_id`. It is your reconciliation key across webhooks, REST reads, and support requests.
* **Send an `Idempotency-Key` on order creation.** A unique key per order attempt makes retries safe: the same key + same body replays the original result instead of double-ordering (and double-charging). Keep `client_order_reference_id` as your reconciliation key - it is not a dedupe key. If you can't send the header, don't blind-retry ambiguous failures (timeout, `5xx`): first list recent orders (`GET /api/v1/orders?since=...`) and check whether your `client_order_reference_id` already appears.
* **Check `available_collection_types` on the variant** before offering `AT_HOME` vs `GO_TO_LAB` to a user, and send the matching address field (`shipping_address` vs `requested_lab_address`).
* **Validate phone numbers with their country code** client-side; the API rejects mismatches with a field-level validation error ([Errors](/vantage-api/errors#validation-errors-on-order-creation)).

## Handling identifiers

* **Store all Vantage IDs as strings.** `order_id`, `order_item_id`, `recipient_id`, `test_taker_id` are 64-bit values serialized as JSON strings; parsing them as doubles (JavaScript's default for numbers) corrupts them.
* **Key your results flow on `order_item_id`**, not `order_id` - activation, result statuses, downloads, and acknowledgment are all per item.
* **Capture `test_taker_id` when it first appears** (the `results.kit_activated` webhook, or any later result webhook). You need it to fetch and acknowledge results. If you miss it, recover it from `GET /api/v1/orders/{orderID}` under `items[].test_taker_ids`.

## Delivering results to your users

* **Re-mint download URLs on demand.** The presigned `download_url` expires after 15 minutes - fetch it when the user opens the result, never store it.
* **Make acknowledgment an explicit user action.** Call the acknowledge endpoint when the user has actually viewed their results - a button or checkbox - never automatically on retrieval. This is a compliance requirement, not a technicality ([Acknowledging Results](/vantage-api/acknowledging-results)).
* **Treat escalations as urgent.** On `results.escalation_raised`, surface the result to the user promptly and acknowledge before `acknowledgment_due_by`; unacknowledged escalations can trigger direct outreach to the patient by medical teams.
* **Handle the failure paths.** Build product flows for `results.sample_rejected` (offer a replacement kit) and `results.lab_processing_error` - they happen in production.

## Environments

* **Build against sandbox first**; it delivers the same signed webhooks as production. Use the [simulate endpoint](/vantage-api/working-with-sandbox#the-simulate-endpoint) in automated tests - it is deterministic and covers failure paths.
* **Remember sandbox and production hold separate webhook URLs**, and `supplier_item_id` appears in sandbox webhook payloads only.
* Before launch, walk the [Going to production](/vantage-api/going-to-production) checklist.


# Going to production

A checklist for moving your Vantage integration from sandbox to production safely.

Sandbox and production are separate environments with separate access: your credentials are enabled for sandbox first, and production is enabled when you are ready to launch (via your Terra contact). Before flipping your integration to `https://vantage.tryterra.co`, walk this checklist.

## Access and configuration

* [ ] **Production access enabled** - confirm with your Terra contact that your account is enabled for production ordering. Sandbox access alone does not open production.
* [ ] **Production markets set** - tell your Terra contact whether you sell in the UK, the US or both. Terra sets a production environment's [markets](/vantage-api/core-concepts#markets); until they are set, it lists every market's products.
* [ ] **Production webhook URL registered** - sandbox and production hold **separate** webhook URLs. Register the production one: `PATCH /api/v1/clients/webhook-url` against `vantage.tryterra.co`, and confirm with `GET /api/v1/clients/webhook-url`.
* [ ] **Base URL switched everywhere** - audit for hard-coded `vantage-sandbox.tryterra.co` references.

## Integration behavior

* [ ] **Signature verification passes in production** - same scheme as sandbox, using your production webhook's signing secret; confirm your first production webhook verifies.
* [ ] **No reliance on sandbox-only behavior:**
  * The **simulate endpoint returns `403` in production** - make sure no product code path calls it.
  * `supplier_item_id` is **absent from production webhook payloads** - if your activation UX needs the kit ID, read it from `GET /api/v1/orders/{orderID}` (`items[].supplier_item_id`) instead.
  * Sandbox auto-generates results on a timer; production results take real-world time (days). Make sure nothing times out waiting.
* [ ] **Duplicate-order protection** - production orders cost real money; ensure ambiguous failures are reconciled before retrying ([Best practices](/vantage-api/best-practices#placing-orders)).
* [ ] **Failure paths built** - `results.sample_rejected` and `results.lab_processing_error` need a real user-facing flow (replacement kit, support contact) in production.

## Compliance

* [ ] **Acknowledgment flow live and user-triggered** - results must be acknowledged by an explicit end-user action before patients can access them; unacknowledged results shift liability to you and escalations have an `acknowledgment_due_by` deadline ([Acknowledging Results](/vantage-api/acknowledging-results)).
* [ ] **Escalation handling** - a plan (and a monitored alerting path in your systems) for `results.escalation_raised` events, including out-of-hours.

## Operations

* [ ] **Monitoring wired up** - watch `GET /api/v1/overview` (webhook failures, missing results) and check `GET /api/v1/webhook-deliveries?outcome=failed` when something looks off ([Monitoring and debugging](/vantage-api/monitoring)).
* [ ] **Reconciliation job scheduled** - a periodic sweep of `GET /api/v1/orders?missing=true` and unacknowledged ready results ([Best practices](/vantage-api/best-practices#webhook-handling)).
* [ ] **Support runbook** - your team knows to quote `order_id` / `order_item_id` / `event_id` (all strings) when contacting Terra support.


# Versioning

How Vantage API versions work: choosing a version per request, your account's pinned version, versioned webhooks, and upgrading.

## Versions are dates

Each Vantage API version is named by a date, such as `2026-10-15`. A breaking change ships under a new date. Additive changes, such as a new field or a new endpoint, land in every version. The [changelog](/vantage-api/changelog) lists every version and what changed in it.

## Choosing a version

Each request is served in one version, picked in this order:

1. The `X-Terra-Version` header on the request, if you send one.
2. Your account's pinned version.

Your account is pinned to the latest version on its first request, so new integrations always start on the latest version and keep it until you upgrade.

Every response carries an `X-Terra-Version` header stating the version it was served in.

```bash
curl 'https://vantage-sandbox.tryterra.co/api/v1/products/1' \
  -u 'YOUR_DEV_ID:YOUR_API_KEY' \
  -H 'X-Terra-Version: 2026-10-29'
```

An unknown version returns `400` with code `invalid_api_version`. The `detail` lists the supported versions. See [Errors](/vantage-api/errors).

## Webhooks

Webhook deliveries use your account's pinned version. The request header does not apply to them. Each delivery carries the version it was rendered in as an `X-Terra-Version` header.

If you process deliveries asynchronously, store the `X-Terra-Version` header with the body, so the worker knows which shape it is reading. See [Webhooks](/vantage-api/webhooks).

## Upgrading

Your pinned version is shown next to the Test mode toggle in the Vantage dashboard. When a newer version exists, you can upgrade from there:

1. Read the [changelog](/vantage-api/changelog) for every version between yours and the latest.
2. Send `X-Terra-Version` with the new date on individual requests, and check your code handles the new shape.
3. Update your webhook handler to accept the new shape, using the `X-Terra-Version` header on each delivery to tell the two apart.
4. Select **Upgrade** in the dashboard's API version menu.

Once the pin changes, requests without the header and all webhook deliveries use the new version. The pin applies to Test mode and Production together.

If something breaks after an upgrade, switch back under **Older versions** in the same menu.


# Changelog

Every Vantage API version, newest first, with its breaking changes and the non-breaking changes shipped while it was the latest.

Each Vantage API version is named by a date. Under each version:

* **Breaking** changes apply only once your account is pinned to that version, or when you send it in the `X-Terra-Version` header. See [Versioning](/vantage-api/versioning) for how to upgrade.
* **Non-breaking** changes reach every version as soon as they ship, with no upgrade needed. They are listed by the date they shipped, under the version that was the latest at the time.

Enums can gain new values without a new version. Treat a value you don't recognise as described in the [API reference](https://docs.tryterra.co/reference/vantage-api).

## `2026-10-29` (latest)

### Breaking

* **Catalogue:** a product's `description` is a [rich text document](/vantage-api/rich-text), a JSON tree with a node for every Markdown construct, instead of a string. A product without a description has an empty document. Variant and product type descriptions are still strings.

### Non-breaking

#### 2026-10-29

* **Catalogue:** each entry in a variant's `biomarkers` has a `summary`, a rich text `description` and a `source_url`: a plain-language explanation of the biomarker, copied from the U.S. National Cancer Institute or MedlinePlus, and the page it came from. All three are `null` when no source explains the biomarker. Every API version serves them. See [Core concepts](/vantage-api/core-concepts#the-catalog-product-types--products--variants).

## `2026-10-15`

### Breaking

* **IDs:** product, variant, image and product type IDs are decimal strings, such as `"42"`, instead of numbers. A request's `variant_id` accepts a string or a number.
* **Orders:** `currency` is the ISO 4217 code (`USD`, `EUR`, `GBP`) instead of the numeric code (`840`, `978`, `826`).
* **Orders:** `item_status` is a string (`pending_shipment`, `in_transit`, `delivery_attempted`, `delivered`) instead of an integer. It is omitted until the kit has a shipping status.
* **Lists:** `GET /orders`, `GET /results` and `GET /webhook-deliveries` return `data`, `has_more` and `next_cursor`, all always present. Previously the items were under `orders`, `results` or `deliveries`, with no `has_more`, and `next_cursor` was omitted on the last page. Catalogue routes and `GET /labs` are unpaginated and still return a bare array.
* **Idempotency:** replaying a request with the same `Idempotency-Key` and body returns `200` instead of `201`.
* **Idempotency:** an `Idempotency-Key` longer than 255 characters returns `400` with code `idempotency_key_too_long`.
* **Errors:** `type` URIs are `https://docs.tryterra.co/vantage-api/errors/<slug>` instead of `https://api.terra-diagnostics.com/errors/<slug>`.
* Webhook payloads are unchanged.

### Non-breaking

#### 2026-10-29

* **Errors:** most credential refusals are `application/problem+json` with a `code`, whatever the version: `unauthorized` (`401`) for a missing, invalid, expired or revoked key or token, `scope_missing` or `audience_restricted` (`403`), and `authorization_unavailable` (`503`, retry later). The status codes are unchanged. A few keep the previous format, so choose the schema by `Content-Type`. [Errors](/vantage-api/errors#credential-refusals)

#### 2026-10-28

* **Orders:** `GET /orders` accepts `order_id`, `variant_id`, `recipient_name` and `recipient_email` filters. `status` takes several statuses.
* **Results:** `GET /results` accepts `variant_id` and `client_order_reference_id` filters. `status` and `order_id` take several values.
* **Lists:** on `GET /orders` and `GET /results`, a list filter takes up to 100 values, repeated or joined with commas, and matches any of them. `order=asc` returns the oldest first. Send the same `order` and filters with every page's cursor.
* **Webhooks:** a webhook URL with credentials in it, such as `https://user:pass@example.com`, returns `400`.

#### 2026-10-27

* **Catalogue:** an environment can be limited to the UK or US market. Once its markets are set, catalog reads leave out products not sold in them, the variants route returns `404` for one, and ordering one returns `403`. Until then it sees every market. See [Markets](/vantage-api/core-concepts#markets).
* **Webhooks:** every event is recorded when it happens. One that could not be sent straight away is sent later under the same `event_id`, so it can arrive after a newer event for the same order: order them by `X-Terra-Ordering-Timestamp`.
* **Webhooks:** in `GET /webhook-deliveries`, `attempts` counts every HTTP attempt across all retries, and a dead-lettered delivery carries its last status code, or `null` when the last attempt got no response.
* **Webhooks:** creating an order sends `order.status_changed` for `order.payment_processing`, and for `order.payment_complete` when payment is taken as the order is created. Previously these two statuses could only be read from the order.

#### 2026-10-09

* **Results:** `results_status` can be `results.not_applicable`, for a product that never produces a result. It never changes, and no results webhook is sent for it.

#### 2026-10-08

* **Catalogue:** variants have a `collection_visit`, `home_phlebotomy` or `clinic`, when the sample is taken at a clinician visit. It is omitted for self-collected kits.
* **Catalogue:** `collection_method` can be `automatic_capillary`, a self-collected capillary sample from a push-button device.
* **Orders:** order items have a `collection_visit` with `type`, `status` (`booking`, `requested` or `booking_failed`) and `scheduling_url`.
* **Orders:** a home-visit item needs an `AT_HOME` order with a valid phone number, or the request returns `400`. A clinic-visit item is ordered as `GO_TO_LAB` with a `shipping_address`, and can have the status `awaiting_clinic_invite`.
* **Orders:** `POST /orders` can return `422` with code `order_not_approved` for a test that needs clinician approval. The same `Idempotency-Key` and body can be retried.
* **Orders:** kit activation returns `409` while another activation of the same kit is in progress. Retry shortly.
* **Webhooks:** `results_ready` carries `amended: true` when it is a corrected release of a result already delivered. Fetch the result again.

#### 2026-10-02

* **Orders:** `GET /orders` accepts `until` and `client_order_reference_id` filters.
* **Results:** `GET /results` accepts `is_acknowledged`, `order_id`, `since` and `until` filters.
* **Lists:** a `limit` above 100 is treated as 100 instead of returning `400`. An exactly full last page no longer returns a `next_cursor`.
* **Idempotency:** a request that failed without creating anything, such as a `402` or a `403` catalogue rejection, can be retried with the same `Idempotency-Key` and body.
* **Payments:** `402` responses carry a `code`: `payment_method_missing`, `card_declined` or `payment_authorization_failed`.
* **Webhooks:** `POST /webhook-events/resend` resends a delivered event for up to 30 days, and `POST /webhook-events/generate` sends a test event marked `"test": true`. Both need the `vantage:write` scope and accept `?dry_run=true`.
* **Webhooks:** every delivery carries `X-Terra-Ordering-Timestamp`, the Unix time in milliseconds the event was emitted. It is the same on every retry.
* **All responses:** carry an `X-Request-Id` header. Include it when you contact support.
* **Fixed:** in result FHIR bundles, every reference now resolves inside the bundle, and each bundle includes an `Organization` entry.

## `2026-10-01`

### Breaking

Catalogue variants carry typed fields. See [Core concepts](/vantage-api/core-concepts).

* **Catalogue:** variant `variant_name` is renamed to `name`.
* **Catalogue:** variant `descriptive_attrs_override` is replaced by `description`.
* **Catalogue:** variant `variant_defining_attrs` is replaced by `turnaround_days` and `collection_method`.
* **Catalogue:** variant `variant_availability` is replaced by `availability`, a string: `unknown`, `in_stock` or `out_of_stock`.
* **Catalogue:** variant `requires_activation` is added.
* **Catalogue:** product `model_descriptive_attrs` is removed. Its collection method is now `collection_method` on each variant.
* **Catalogue:** product `availability` is a string instead of an integer.
* Webhook payloads are unchanged.

### Non-breaking

#### 2026-10-01

* **Catalogue:** product and variant `images` are populated.

#### 2026-09-29

* **Versioning:** your account is pinned to the latest version on its first request, and you can change the pin in the dashboard.

#### 2026-09-28

* **Versioning:** the `X-Terra-Version` header picks the version a request is served in. Every response and webhook delivery carries it, and an unknown value returns `400` with code `invalid_api_version`.

## `2026-09-27`

The first version. Catalogue variants carry attribute bags and integer availability.


# Overview

Let your AI agents read a user's health data directly over MCP, without building an API integration, handling webhooks, or storing and parsing data yourself.

Terra AI lets your AI agents interface with Terra's health data directly through an [MCP](https://modelcontextprotocol.io) (Model Context Protocol) server. The server gives your agent the tools and context it needs to query a user's data and reason over it.

Through Terra AI, your agent can:

1. Request only specific, relevant datasets
2. Access a user's health memory
3. Access aggregated stats, trends, and baselines
4. Access the semantic meaning of health data

{% hint style="info" %}
**Terra AI is not a tool for writing Terra code.** Terra AI reads your users' health data at runtime. To help your coding agent write a Terra integration, install the [Agent skills](https://docs.tryterra.co/developer-tools/agent-skills) and the [Terra CLI](https://docs.tryterra.co/developer-tools/terra-cli/terra-cli), which answers questions from these docs with `terra docs ask --question`. To let an assistant manage your Terra account, use the [MCP server](https://docs.tryterra.co/developer-tools/mcp-server) in Developer Tools.
{% endhint %}

## Why we built Terra AI

We built Terra AI so your AI agents can retrieve and reason over health data in the most token-efficient way.

You don't have to make API calls, handle webhooks, trigger backfills, or store and parse data. Your agent retrieves only meaningful, relevant data for reasoning, without overfetching or bloating its context window.

## Quick install

Add the MCP configuration to your client to get started. Below are setup guides for some example AI IDEs, but you can use Terra AI with any system that supports MCP.

You need to include your `dev-id` and `x-api-key` in the HTTP headers. You can find these on the [Terra dashboard](https://dashboard.tryterra.co) under **API keys**. The `user_id` is passed as part of the server URL.

{% tabs %}
{% tab title="Claude Code" %}
In your terminal, run the following command:

```bash
claude mcp add --transport http terra-ai https://access.tryterra.co/api/v2/mcp/<user_id> \
  --header "dev-id: <YOUR_DEV_ID>" \
  --header "x-api-key: <YOUR_API_KEY>"
```

{% endtab %}

{% tab title="Claude desktop" %}

1. In Claude Desktop, navigate to **Settings > Developer**
2. Select **Edit Config** to open the configuration file
3. Paste the following into **claude\_desktop\_config.json**

```json
{
  "mcpServers": {
    "terra-ai": {
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Cursor" %}

1. Open Cursor, then navigate to **Cursor Settings > Tools & Integrations**
2. Select **New MCP Server**
3. Paste the following into **mcp.json**

```json
{
  "mcpServers": {
    "terra-ai": {
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="VS Code" %}

1. Open VS Code, then open the configuration file by running `MCP: Open User Configuration` in the command palette
2. Paste the following into **mcp.json**

```json
{
  "servers": {
    "terra-ai": {
      "type": "http",
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Windsurf" %}

1. Open Windsurf, then navigate to **Windsurf Settings > Cascade > MCP servers**
2. Select **Manage MCP Servers**
3. Select **View raw config**
4. Paste the following into **mcp\_config.json**

```json
{
  "mcpServers": {
    "terra-ai": {
      "url": "https://access.tryterra.co/api/v2/mcp/<user_id>",
      "headers": {
        "dev-id": "YOUR_DEV_ID",
        "x-api-key": "YOUR_API_KEY"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Replit" %}

1. Open Replit, navigate to the **Integrations** page, and scroll down to MCP Servers for **Replit Agent**
2. Select **Add MCP server**
3. Enter the server URL `https://access.tryterra.co/api/v2/mcp/<user_id>`
4. Add custom headers: your `dev-id` and your `x-api-key`
5. Select **Test & Save**
   {% endtab %}
   {% endtabs %}

## Available tools

Tools are functions your AI agent calls to get specific health data. They can query specific data and perform aggregations.

Each tool takes parameters such as `user_id`, a list of data fields, and optional filter conditions. For the full list of data fields available to each tool, see [data models](https://docs.tryterra.co/reference/health-and-fitness-api/data-models).

| Tool                    | Purpose                           | Example fields                                                                                                                                                                                                              |
| ----------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get_sleep_data`        | Sleep quality and quantity        | Sleep start and end time, total sleep, REM, deep and light sleep, sleep latency, average and resting HR, average HRV, respiratory rate, average SpO2, sleep score                                                           |
| `get_activity_data`     | Activity and workout sessions     | Activity start and end time, activity type, location, active, inactive and rest time, intensity bands, total distance, step count, floors climbed, swimming laps                                                            |
| `get_daily_data`        | Whole-day health summaries        | Average, maximum, minimum and resting heart rate, average and minimum HRV, average SpO2, total and net active calories, activity time, daily distance and steps, stress duration, strain level, recovery and activity score |
| `get_body_data`         | Body measurements                 | Water consumption, VO2 max estimate, average SpO2, blood pressure, measurements, temperature, ketones, ECG data                                                                                                             |
| `get_nutrition_data`    | Nutrients and calorie consumption | Total calories, protein, carbohydrates, total, trans and saturated fat, sugar, cholesterol, fiber, vitamins, micronutrients, amino acids                                                                                    |
| `get_menstruation_data` | Menstrual cycle and fertility     | Cycle start and end time, period start date, current phase and its length, days until next phase, predicted and actual cycle length, fertility window start and end, predicted ovulation day                                |

## Example scenarios

Prompts your AI agent can answer once connected to Terra AI:

**Health insights and analysis**

* Give me a complete health snapshot: sleep, activity, stress, and recovery for this week
* Show me the relationship between my sleep quality and next-day performance
* What's my longest streak of days with at least 7 hours of sleep?

**Pattern recognition and correlations**

* Show me the correlation between my sleep latency and my stress level
* What's my average resting heart rate on days after poor sleep vs good sleep?

**Training and recovery optimisation**

* What's my optimal recovery time between high-intensity workouts?
* Find all days where I had a low recovery score but still did intense workouts

**Predictive and proactive insights**

* What's my predicted recovery time for tomorrow based on today's workout?
* Based on my HRV trends, should I train hard or take it easy today?

## What Terra AI includes

Terra AI's MCP server exposes three primitives:

1. **Tools**: functions your agent calls to get specific health data, and to perform aggregations. For example, the sleep tool can analyse a user's sleep architecture between 12 November 2025 and 30 November 2025.
2. **Resources**: context about the available data and how the data schema is structured.
3. **Prompts**: text-based templates that help your agent understand how to use the tools and retrieve data from the resources.

## Next steps

* [Error states](/ai-interface/error-states) covers what your agent sees when a call fails, and what is not guaranteed.


# Error states

The HTTP statuses and error detail strings Terra AI guarantees, split by whether the failure happens before or after a tool call starts.

There are two distinct error surfaces:

1. **Session or transport failures.** These are returned before any tool execution begins.
2. **Tool-call failures.** These are returned after a tool invocation starts.

## Session or transport failures

### Response format

When a session or transport failure returns a structured HTTP error, the response is:

```http
Content-Type: application/problem+json
```

with this body shape:

```json
{
  "type": "about:blank",
  "title": "<http status text, lowercased>",
  "instance": "<request URL>",
  "detail": "<error detail>"
}
```

Some transport failures return only an HTTP status code and an empty body. Those cases are called out explicitly below.

### Guaranteed session and transport errors

| HTTP status | Body         | Detail                                    | When it is returned                                              |
| ----------- | ------------ | ----------------------------------------- | ---------------------------------------------------------------- |
| `401`       | problem JSON | `dev-id or x-api-key headers are missing` | Client credentials are missing.                                  |
| `401`       | problem JSON | `unauthorized`                            | Client credentials are invalid.                                  |
| `404`       | problem JSON | `missing user_id parameter`               | The required user identifier is missing.                         |
| `404`       | problem JSON | `invalid user id`                         | The supplied user identifier is malformed or not authorised.     |
| `500`       | problem JSON | `something went wrong`                    | A server-side failure occurs before MCP execution starts.        |
| `500`       | empty body   | none                                      | A server-side transport configuration failure prevents proxying. |
| `502`       | empty body   | none                                      | The MCP upstream is unavailable or unreachable.                  |

### Client handling

* Do not retry `401` or `404` without changing the request.
* Treat `500` and `502` as server-side failures.
* Retry `502` with backoff.

## Tool-call failures

Once a tool call begins, Terra-defined validation and query-construction failures surface as MCP tool errors.

### Return contract

For tool-call failures, Terra guarantees the error detail string listed below.

The exact outer MCP error envelope is produced by the MCP runtime, so this page only guarantees the tool error detail text, not the full wrapper shape.

### Guaranteed tool error details

**Query shape validation**

| Error detail                           | When it is returned                                        |
| -------------------------------------- | ---------------------------------------------------------- |
| `fields or select are required`        | Neither `fields` nor `select` was provided.                |
| `fields and select cannot both be set` | Both `fields` and `select` were provided in the same call. |

**Request context failures**

| Error detail                          | When it is returned                                               |
| ------------------------------------- | ----------------------------------------------------------------- |
| `request context is unavailable`      | The tool did not receive the request context required to execute. |
| `Provider-User-Id header is required` | The tool did not receive the required user context header.        |

Treat these as server-side failures rather than malformed client input.

**Timestamp filter validation**

| Error detail                                                                   | When it is returned                                              |
| ------------------------------------------------------------------------------ | ---------------------------------------------------------------- |
| `Only the IN operator accepts a list of timestamps`                            | A timestamp filter used a list with an operator other than `IN`. |
| `IN timestamp filters require at least one timestamp`                          | A timestamp `IN` filter was empty.                               |
| `Invalid ISO 8601 timestamp '<value>'. Use formats like 2025-11-12T00:00:00Z.` | A timestamp value was not valid ISO 8601.                        |
| `Only timestamp fields support list values via IN`                             | A list value was provided for a non-timestamp field.             |

**Logical filter validation**

| Error detail                                        | When it is returned                                        |
| --------------------------------------------------- | ---------------------------------------------------------- |
| `And condition provided but empty after conversion` | An `and` clause contained no usable subconditions.         |
| `Or condition provided but empty after conversion`  | An `or` clause contained no usable subconditions.          |
| `Not condition was None after conversion`           | A `not` clause could not be converted into a valid filter. |

### Client handling

* Do not retry tool-call validation failures without changing the tool input.
* Surface the returned detail string directly to developers.
* Treat request-context failures as server-side errors.

## What is not guaranteed here

This page intentionally does not guarantee:

* the full outer MCP error envelope for tool-call failures
* validation messages generated solely by the MCP runtime or model layer
* error messages for malformed requests that fail before reaching Terra's own validation logic

Only the statuses and detail strings listed above are guaranteed by Terra's implementation.


# Overview

Run Terra's health models over your users' data to turn raw metrics into ready-to-use wellness insights.

**Models** run Terra's health models over a user's data and return ready-to-use insights, with no extra data collection, no model to host yourself. You call one endpoint with a `user_id` and a date range, and Terra returns the result.

Every model is a **wellness indicator, not a medical or diagnostic tool.**

You can run models two ways, and they behave identically:

* **From the API**: call the endpoint below with your API key. This is the same request the dashboard makes.
* **From the Terra Dashboard**: open **Models**, pick a model and a user, and click **Run**.

{% hint style="success" %}
**Prerequisites.** You need:

1. **API Key & dev-id**: obtain both from your [Terra Dashboard](https://dashboard.tryterra.co/).
2. **A connected user**: models run over a connected user's data, so you need at least one connected `user_id`.
   {% endhint %}

***

## Available models

Three models are generally available today; more are in active development.

| Model                       | `model` id            | What it returns                                                                                                                                                                                       |
| --------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Sleep Window**            | `sleep_window`        | A steady, personalised sleep schedule (recommended bed and wake times) to help keep a user's sleep timing consistent. More regular sleep timing is associated with better recovery and sleep quality. |
| **Menstrual Cycle Tracker** | `cycle_phase_tracker` | A per-day cycle phase, plus the period onsets and fertile windows detected in a user's overnight physiology. No logged period dates are needed or read.                                               |
| **Smart Fill**              | `graph_impute`        | Reconstructs the metrics a user's device did not record for a day, alongside the ones it did, with a confidence on each reconstructed value.                                                          |

***

## List available models

Returns the models you can run.

```bash
curl --request GET 'https://api.tryterra.co/v2/models' \
  --header 'x-api-key: YOUR_API_KEY' \
  --header 'dev-id: YOUR_DEV_ID'
```

```json
{
  "status": "success",
  "models": [
    { "id": "sleep_window", "name": "Sleep Window", "description": "…", "data_type": "sleep" },
    { "id": "cycle_phase_tracker", "name": "Menstrual Cycle Tracker", "description": "…", "data_type": "cycle" },
    { "id": "graph_impute", "name": "Smart Fill", "description": "…", "data_type": "sleep, daily or activity" }
  ]
}
```

***

## Run a model

Runs the chosen model over one user's data for a date range and returns its result. It is read-only and does not trigger a new data pull from the provider.

**`GET https://api.tryterra.co/v2/models/run`**

| Parameter    | In     | Description                                                                                                                                                                           |
| ------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `x-api-key`  | header | Your Terra API key.                                                                                                                                                                   |
| `dev-id`     | header | Your developer id.                                                                                                                                                                    |
| `model`      | query  | The model id, e.g. `sleep_window`.                                                                                                                                                    |
| `user_id`    | query  | The Terra user to run the model over.                                                                                                                                                 |
| `start_time` | query  | Start of the window (ISO 8601).                                                                                                                                                       |
| `end_time`   | query  | End of the window (ISO 8601).                                                                                                                                                         |
| `table`      | query  | **Smart Fill only, and required for it**: which table to reconstruct: `sleeps`, `dailies` or `activities`. The three carry different metrics, so the model will not pick one for you. |

```bash
curl --request GET \
  'https://api.tryterra.co/v2/models/run?model=sleep_window&user_id=USER_ID&start_time=2026-04-01T00:00:00Z&end_time=2026-07-01T00:00:00Z' \
  --header 'x-api-key: YOUR_API_KEY' \
  --header 'dev-id: YOUR_DEV_ID'
```

**Sleep Window** returns a recommended schedule and how consistent the user already is:

```json
{
  "status": "success",
  "model": "sleep_window",
  "data_type": "sleep_window",
  "user_id": "USER_ID",
  "provider": "OURA",
  "window": {
    "recommended_bed": "23:04",
    "recommended_wake": "07:06",
    "in_bed_h": 8.0,
    "approximate": false
  },
  "sleep_regularity": { "score": 64, "band": "Fair" },
  "recommendation": {
    "change": "Close your weekend gap",
    "reason": "you sleep ~57 min later on weekends",
    "moves_to": "Good",
    "gain": 8
  }
}
```

`approximate` is `true` when the schedule is estimated from limited history. `sleep_regularity.score` is a 0–100 index with a band of Low / Fair / Good / Excellent. `recommendation` names the single change that would raise the score most, and is absent when the user is already consistent.

Sleep Window reads the user's whole history rather than the range you pass, so `start_time` and `end_time` do not change its answer.

**Menstrual Cycle Tracker** returns one row per calendar day of the range, plus the cycles it detected:

```json
{
  "status": "success",
  "model": "cycle_phase_tracker",
  "data_type": "cycle",
  "user_id": "USER_ID",
  "provider": "OURA",
  "temperature_used": true,
  "detected_onsets": 16,
  "regularity": "regular",
  "results": [
    {
      "date": "2026-05-01",
      "phase": "luteal",
      "period": true,
      "period_confidence": "high",
      "fertile": false,
      "available": true
    }
  ],
  "periods": [
    { "onset_date": "2026-05-01", "end_date": "2026-05-05", "band": "high" }
  ],
  "fertile_windows": [
    { "start_date": "2026-05-15", "end_date": "2026-05-18", "ovulation_date": "2026-05-15" }
  ]
}
```

`results` holds one row per day in the range **including days the model had no data for**, so check `available` rather than assuming every row is an answer. `period` and `fertile` say what was detected; the matching `*_confidence` is a band of low / medium / high. Read the bands, not raw probabilities. A period day is never also a fertile day.

`temperature_used` tells you which variant ran. Skin temperature makes the reading materially more precise, and the model only uses it where it can be placed in the feature space it was trained on: natively for Oura, through its device mapping for Fitbit. Every other device is scored by a dedicated temperature-free variant even when it reports a temperature of its own.

The tracker needs at least 30 days of overnight history with heart rate and HRV. It is a wellness indicator, **not a medical or contraceptive tool.**

**Smart Fill** returns the day's metrics, marking which were reconstructed:

```json
{
  "status": "success",
  "model": "graph_impute",
  "table": "sleeps",
  "provider": "OURA",
  "features": ["hr_average", "hrv_average", "..."],
  "results": [
    {
      "date": "2026-05-01",
      "history_days": 62,
      "fields": [
        { "feature": "hr_average", "value": 58.4, "computed": false, "reported": true },
        { "feature": "hrv_average", "value": 41.2, "computed": true, "confidence": "high", "reported": false }
      ]
    }
  ]
}
```

`computed: true` marks a value the model reconstructed and `reported: true` a value the device actually recorded, so you can always tell them apart. A reconstructed value carries a `confidence`. Smart Fill needs a `table` (see above) and returns recorded values alongside reconstructed ones, so a scoped token needs `data:read` as well as `models:run`; a plain API key is unaffected.

{% hint style="warning" %}
**Supported devices and data.** Each model needs the right kind of data. If a user's device isn't supported, or there isn't enough history yet, the response returns `unsupported: true` (with an `unsupported_reason` and the list of supported devices) or an empty result rather than an error, so you can message the user accordingly.
{% endhint %}

***

## Pricing

Model runs are **usage-based: 1 credit per run, and each credit costs $0.01**, drawn from your plan's monthly credit allowance. See [Pricing](/unified-api/pricing). A run over one user for one date range is one credit, regardless of how much data it covers.


# Overview

Build a chart of your users' health data in the Terra dashboard, then drop it into your product.

Graphs turn a user's health data into a chart you can put in your product: steps, resting heart rate, glucose, sleep stages, or any other field Terra collects.

You build each graph once in the Terra dashboard: pick the metric, choose a style, set the colours. Terra gives you an id. Your app renders that graph for whichever user is looking at it.

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-7b3513005a2d89e0334fac742f2e356494a8ccca%2Fgraphs-examples.png?alt=media" alt="Four Terra graphs: daily steps, resting heart rate with a baseline, sleep stages, and heart-rate zones"><figcaption><p>Four graphs, all built in the dashboard with no code</p></figcaption></figure>

Nothing about a graph's design lives in your codebase. Change the metric, the chart type or the colours in the dashboard and every embed updates. No deploy, no release.

{% hint style="info" %}
Graphs are an add-on. If you don't see them in your dashboard yet, open **Graphs** and choose **Unlock Graph API**, or talk to your account manager.
{% endhint %}

***

## Build your first graph

{% stepper %}
{% step %}

#### Open Graphs and create one

Go to [**Dashboard → Graphs**](https://dashboard.tryterra.co/dashboard/graphs) and choose **New graph**. An editor opens with a live preview beside it, drawn with generated data so you can see the result immediately.
{% endstep %}

{% step %}

#### Choose what to plot

Under **Data**, pick one of:

* **Metric**: any numeric field Terra collects. Search for what you want (`Steps`, `Resting HR`, `Glucose`) and select it. Add more to plot them together, each as a line or a bar: daily summaries combine freely, and sampled metrics from the same record (heart rate and power from one workout) overlay. Picking something that can't share an axis with your current selection replaces it rather than adding to it.
* **Specialty**: a pre-built chart that combines several fields into one designed layout: sleep stages, a macro breakdown, or an ambulatory glucose profile.

For metrics recorded as continuous samples, such as heart rate during a workout or glucose through the day, a **Scope** control appears. **Over time** trends the metric across your whole date range. **Single session** zooms into the most recent workout, night or day, and keeps following the latest one as new data arrives.
{% endstep %}

{% step %}

#### Style it

**Quick style** applies a complete look in one click, and the options offered depend on what you picked:

| Quick style          | What it shows                                                                              |
| -------------------- | ------------------------------------------------------------------------------------------ |
| **Minimal**          | Icon, title, and the latest value.                                                         |
| **Stats + baseline** | Average, lowest and highest, with an average reference line and the extremes marked.       |
| **Heart-rate zones** | Training-zone bands behind the line, with the peak marked. Offered for heart-rate metrics. |
| **Min/max range**    | Per-day min/max whiskers with a range in the header. Offered for sampled metrics.          |

Everything a quick style sets stays editable underneath it, so you can start from one and adjust. Under **Theme**, pick a preset (Light, Midnight, Forest, Sunset, Plum, Mono) or set the background, line, text and tick colours yourself. The preview restyles as you go.

Give the graph a **Title** if you want something other than the metric name.
{% endstep %}

{% step %}

#### Save it and copy the id

Choose **Save**. The graph appears as a card on the Graphs page. Select **Embed** on the card to get its id along with ready-made snippets.

That id is all your app needs.
{% endstep %}
{% endstepper %}

***

## Show it to a user

A graph is a template. You build one and render it for each of your users. Rendering takes two ids:

* the **graph id**, from the dashboard
* a **user id**, the Terra user whose data to draw

{% tabs %}
{% tab title="React" %}

```bash
npm install @tryterra/graphs-react
```

```jsx
import { TerraGraph } from "@tryterra/graphs-react";

<TerraGraph
  sessionId="YOUR_GRAPH_ID"
  userId={terraUserId}
  timeframe={30}
  style={{ width: "100%", height: 360 }}
/>
```

{% endtab %}

{% tab title="HTML" %}

```bash
npm install @tryterra/graphs
```

```html
<script type="module">
  import "@tryterra/graphs";
</script>

<terra-graph
  session-id="YOUR_GRAPH_ID"
  user-id="TERRA_USER_ID"
  timeframe="30"
  style="display: block; width: 100%; height: 360px;"
></terra-graph>
```

{% endtab %}

{% tab title="iframe" %}

```html
<iframe
  src="https://api.tryterra.co/v2/graphs/YOUR_GRAPH_ID/TERRA_USER_ID?timeframe=30"
  width="100%"
  height="360"
  frameborder="0"
  title="Daily steps"
></iframe>
```

{% endtab %}
{% endtabs %}

Use `example` in place of a user id to render generated data. This is useful while you build the layout, before you have a connected user.

React Native draws graphs natively with its own package; Vue, Svelte, Angular, iOS, Android and Flutter are all covered in [Embedding graphs](/graphs/embedding).

***

## Who can see a graph

The graph id and user id both go in your frontend, and neither is a credential. Your API key stays on your server.

A graph renders only for users connected to your Terra account, and only that user's data. But anyone holding both ids can load the chart, so treat an embed URL the way you'd treat a link to a shared document: fine to give the person whose data it is, not something to publish. Render each user's graph with their own id, and don't put embed URLs anywhere a different user could pick them up.

The **Viewers** action on a graph card shows which of your users have loaded it, and when.

***

## What a graph can plot

Almost anything Terra collects. The metric picker searches every numeric field across activities, dailies, sleep, body and nutrition, so if a value appears in a Terra payload you can chart it. Some common ones:

| Data type     | Examples                                                                      |
| ------------- | ----------------------------------------------------------------------------- |
| **Daily**     | Steps, distance, active calories, resting heart rate, stress                  |
| **Sleep**     | Time asleep, REM/light/deep duration, sleep heart rate, HRV, respiratory rate |
| **Activity**  | Heart rate, power, cadence, speed, elevation, calories                        |
| **Body**      | Glucose, weight, blood pressure, SpO₂, temperature                            |
| **Nutrition** | Calories, macros, water, individual micronutrients                            |

Specialty graphs cover the charts that need more than one field: **sleep stages** as a hypnogram with a stage breakdown, **macro breakdown** as stacked daily macros against calories, and **ambulatory glucose profile** as percentile bands across the day.

{% hint style="info" %}
A graph draws the data Terra already holds for that user. If a chart looks empty, the usual cause is that no data has arrived for that date range yet. Check the user in [**Dashboard → Users**](https://dashboard.tryterra.co/dashboard/users).
{% endhint %}

***

## Next

* [**Embedding graphs**](/graphs/embedding): every framework, React Native and mobile, date ranges, theming, and what to do when a graph doesn't render.


# Pricing

The Graph API is a paid add-on, billed per pair of graphs. It does not use credits.

## The add-on

The Graph API adds interactive health data graphs to your app. It costs **$50/month for every 2 graphs**, rounded up to the next pair: 1 or 2 graphs cost $50 a month, 3 or 4 cost $100. It does not use credits.

Activate it from the dashboard: open **Graphs** and choose **Unlock Graph API**.

## How graphs are counted

Each graph you set up in a production environment counts toward the total. Graphs in testing and staging environments are free, so you can build and test before going live.

See [Pricing](/unified-api/pricing) for the Quick Start plan and the other add-on products.


# Embedding graphs

Put a graph you built in the dashboard into your web or mobile app.

Every embed needs the same two things: the **graph id** from [**Dashboard → Graphs**](https://dashboard.tryterra.co/dashboard/graphs) (select **Embed** on a card to copy it) and the **Terra user id** of the person looking at it.

Use `example` in place of a user id to render generated data while you build.

***

## Web

On the web, graphs render directly into your page. There's no iframe, so the chart sizes to its container, inherits your layout, and behaves like any other element.

{% tabs %}
{% tab title="React" %}

```bash
npm install @tryterra/graphs-react
```

```jsx
import { TerraGraph } from "@tryterra/graphs-react";

export function StepsCard({ terraUserId }) {
  return (
    <TerraGraph
      sessionId="YOUR_GRAPH_ID"
      userId={terraUserId}
      timeframe={30}
      style={{ width: "100%", height: 360 }}
      onError={(error) => console.error(error.message, error.traceId)}
    />
  );
}
```

Works in Next.js, Remix and Astro with no `dynamic()` wrapper. The component renders nothing on the server and mounts in the browser.
{% endtab %}

{% tab title="HTML" %}

```bash
npm install @tryterra/graphs
```

```html
<script type="module">
  import "@tryterra/graphs";
</script>

<terra-graph
  session-id="YOUR_GRAPH_ID"
  user-id="TERRA_USER_ID"
  timeframe="30"
></terra-graph>

<style>
  terra-graph { display: block; width: 100%; height: 360px; }
</style>
```

{% endtab %}

{% tab title="Vue" %}

```bash
npm install @tryterra/graphs
```

Tell the Vue compiler that `terra-graph` is a custom element, in `vite.config.js`:

```js
vue({ template: { compilerOptions: { isCustomElement: (tag) => tag === "terra-graph" } } });
```

```vue
<script setup>
import "@tryterra/graphs";
defineProps(["graphId", "terraUserId"]);
</script>

<template>
  <terra-graph :session-id="graphId" :user-id="terraUserId" timeframe="30" />
</template>
```

{% endtab %}

{% tab title="Svelte" %}

```bash
npm install @tryterra/graphs
```

```svelte
<script>
  import "@tryterra/graphs";
  export let graphId;
  export let terraUserId;
</script>

<terra-graph session-id={graphId} user-id={terraUserId} timeframe="30" />

<style>
  terra-graph { display: block; width: 100%; height: 360px; }
</style>
```

{% endtab %}

{% tab title="Angular" %}

```bash
npm install @tryterra/graphs
```

```ts
import "@tryterra/graphs";
import { Component, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";

@Component({
  selector: "app-steps",
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `
    <terra-graph
      [attr.session-id]="graphId"
      [attr.user-id]="terraUserId"
      timeframe="30"
    ></terra-graph>
  `,
})
export class StepsComponent {
  graphId = "YOUR_GRAPH_ID";
  terraUserId = "TERRA_USER_ID";
}
```

{% endtab %}
{% endtabs %}

The element has no height of its own. Give it one, or it collapses.

{% hint style="info" %}
The chart engine is loaded from Terra when a graph mounts, which is what keeps every embed in step with the dashboard. If you run a Content Security Policy, allow `script-src https://api.tryterra.co`, `connect-src https://api.tryterra.co`, and, to keep Terra's typeface, `font-src https://fonts.gstatic.com` and `style-src https://fonts.googleapis.com`.
{% endhint %}

***

## React Native

React Native has a package of its own, which draws the graph as native views, with no web view:

```bash
npm install @tryterra/graphs-react-native
```

```jsx
import { TerraGraph } from "@tryterra/graphs-react-native";

<TerraGraph
  sessionId="YOUR_GRAPH_ID"
  userId={terraUserId}
  timeframe={30}
  height={240}
/>
```

There is no chart engine to install or configure. The package ships its own. The one thing it can't bundle is a drawing surface, since React Native has none built in: `react-native-svg` is a native module, declared as a peer so npm installs it for you.

On Expo, run `npx expo install react-native-svg` once afterwards so the version matches your SDK.

For faster painting on very dense charts, import `@tryterra/graphs-react-native/skia` instead and add `@shopify/react-native-skia` and `react-native-reanimated`. Same component, same props.

{% hint style="info" %}
`react-native-svg` ships inside Expo Go, so this runs there as-is, with no development build needed. If you would rather add no native modules at all, use the web view below.
{% endhint %}

**One difference worth knowing.** On the web, the chart engine is loaded from Terra at render time, so improvements reach your users as soon as we ship them. A native app bundles it instead, so it picks them up when you upgrade the package and release a new build. If you would rather never think about that, the web view below is the option that keeps it.

***

## Other mobile platforms

iOS, Android and Flutter load the hosted graph in a web view. React Native can too, with `react-native-webview`, if you would rather not add a charting library:

```
https://api.tryterra.co/v2/graphs/YOUR_GRAPH_ID/TERRA_USER_ID?timeframe=30
```

{% tabs %}
{% tab title="Swift" %}

```swift
import SwiftUI
import WebKit

struct TerraGraph: UIViewRepresentable {
    let graphId: String
    let userId: String

    func makeUIView(context: Context) -> WKWebView { WKWebView() }

    func updateUIView(_ webView: WKWebView, context: Context) {
        let url = URL(string: "https://api.tryterra.co/v2/graphs/\(graphId)/\(userId)?timeframe=30")!
        webView.load(URLRequest(url: url))
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
@Composable
fun TerraGraph(graphId: String, userId: String) {
    AndroidView(factory = { context ->
        WebView(context).apply {
            settings.javaScriptEnabled = true
            loadUrl("https://api.tryterra.co/v2/graphs/$graphId/$userId?timeframe=30")
        }
    })
}
```

{% endtab %}

{% tab title="Flutter" %}

```dart
import 'package:webview_flutter/webview_flutter.dart';

final controller = WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..loadRequest(Uri.parse(
    'https://api.tryterra.co/v2/graphs/$graphId/$terraUserId?timeframe=30',
  ));

// in build():
WebViewWidget(controller: controller)
```

{% endtab %}
{% endtabs %}

The same URL works in an `<iframe>` on the web, if you'd rather not add a package.

***

## Choosing the date range

Every embed takes the same three settings: as props in React, attributes in HTML, and query parameters in a URL.

| Setting                                | Renders                                   |
| -------------------------------------- | ----------------------------------------- |
| `timeframe` = 30                       | The most recent 30 days, including today. |
| `from` = 2026-08-01, `to` = 2026-08-31 | 1–31 August, with `to` included.          |
| `timeframe` = 7, `from` = 2026-08-01   | Seven days starting 1 August.             |
| `timeframe` = 7, `to` = 2026-08-31     | The seven days ending 31 August.          |
| `from` = 2026-08-01                    | 1 August through today.                   |

Dates are `YYYY-MM-DD` in UTC. A range can cover at most **92 days**. With nothing set, you get the last 7 days.

{% hint style="warning" %}
**Pass a date string, not a JavaScript `Date`.** A graph window is a run of calendar days, and a `Date` is a moment in time. Converting one to the other picks a timezone, and the usual way of doing it picks the wrong one. A date picker gives you `new Date(2026, 7, 1)` for "1 August", and `.toISOString().slice(0, 10)` turns that into `2026-07-31` for anyone east of Greenwich.

The packages type these as `IsoDate`, so a `Date` won't compile. If you have one, convert it with the helper they export:

```jsx
import { toIsoDate } from "@tryterra/graphs-react";

<TerraGraph sessionId={graphId} userId={terraUserId} from={toIsoDate(picked)} />
```

{% endhint %}

Changing the range redraws the chart in place rather than reloading it, so you can wire a date picker straight to it:

```jsx
const [days, setDays] = useState(30);

<>
  <RangePicker value={days} onChange={setDays} />
  <TerraGraph sessionId={graphId} userId={terraUserId} timeframe={days} />
</>
```

A graph set to **Single session** scope ignores the range and always shows the user's latest workout, night or day.

***

## Matching your app's theme

A graph's colours are part of its design in the dashboard, so the usual answer is to set them there. Every embed picks the change up without a release on your side.

For colours that have to follow the app at runtime, such as a dark-mode toggle, pass a theme:

```jsx
<TerraGraph
  sessionId={graphId}
  userId={terraUserId}
  theme={isDark ? { bg: "#0F172A", text: "#E2E8F0", line: "#38BDF8" } : undefined}
/>
```

It's a `theme` property on the element too, if you aren't using React:

```js
document.querySelector("terra-graph").theme = { bg: "#0F172A", text: "#E2E8F0" };
```

Give colours as hex or `rgb()`. If you need two colour schemes of the same chart, building two graphs in the dashboard is usually simpler than theming at runtime.

***

## When a graph doesn't render

A graph that can't be drawn says so in place, and reports a **trace id**. Quote that id to Terra support and we can see exactly what happened.

```jsx
<TerraGraph sessionId={graphId} userId={terraUserId} onError={(e) => report(e.message, e.traceId)} />
```

On the element it's a `terra-graph:error` event carrying the same thing, plus a `data-state` attribute (`loading`, `ready` or `error`) and `data-trace-id` on failure.

The common causes:

| What you see                           | Usually means                                                                                                                                                     |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **No data found for this time period** | Terra holds no data for that user over that range. Check the user in [**Dashboard → Users**](https://dashboard.tryterra.co/dashboard/users), and widen the range. |
| **Invalid graph session ID**           | The graph id is wrong, or the graph was deleted. Copy it again from **Embed**.                                                                                    |
| **Invalid graph type requested**       | The graph was created against an old graph type. Open it in the editor and re-pick the metric.                                                                    |
| Nothing renders, no error              | The element has no height. Give it one in CSS.                                                                                                                    |
| A blocked request in the console       | A Content Security Policy is blocking `api.tryterra.co`. See the note above.                                                                                      |

***

## Changing a graph after you've shipped

Graph ids are stable. Edit a graph in the dashboard (different metric, different colours, an extra header stat) and every embed of it changes on the next load. You don't need to touch your app.

Deleting a graph stops it rendering everywhere it's embedded, so check **Viewers** first if you're not sure who's using it.


# Health Scores

Learn how to embed adaptive health scores in your app

## Overview

The **Terra Health Scores** product provides **14 proprietary, science-backed scores** designed to give your users a deeper understanding of their health, recovery, and training load. Scores are organized by which payload they enrich:

* **Daily summary** scores: Immunity Index, Strain Index, Resilience, Respiratory Health, Training Stress (V1 & V2)
* **Sleep** scores: Sleep Score (V1 & V2), Readiness, Respiratory Health V2
* **Activity** scores: Activity Strain, Activity Efficiency, Activity RCRS, Activity TRIMP

Each score is powered by Terra’s proprietary models and translates complex physiological data into a single, interpretable health signal.

The scores are:

* **Device agnostic:** They work across all supported wearable sources as long as the underlying metrics (HRV, sleep stages, respiratory rate, heart rate, etc.) are collected.
* **Turnkey:** No additional backend setup is needed.
* **Continuously generated:** Once a user is connected, scores appear automatically in the `daily`, `sleep`, or `activity` payloads.

***

## How it works

As soon as your users connect their wearables and data begins syncing, Terra will enrich your payloads with the following scores under the `data_enrichment` field.

### Daily payload

<table><thead><tr><th width="220">Score</th><th width="180">JSON field</th><th>Frequency</th><th>Source Data Needed</th></tr></thead><tbody><tr><td>🛡️ <strong>Immunity Index</strong></td><td><code>immune_index</code></td><td>With every new daily payload</td><td>HRV, respiratory rate, body temperature</td></tr><tr><td>💪🏻 <strong>Strain Index</strong></td><td><code>strain_index</code></td><td>With every new daily payload</td><td>HRV (7-day and 28-day baselines), average heart rate</td></tr><tr><td>🌱 <strong>Resilience</strong></td><td><code>resilience_score</code></td><td>With every new daily payload</td><td>Body temperature, respiratory rate, RHR, HRV, oxygen saturation (with 30-day baselines)</td></tr><tr><td>🫁 <strong>Respiratory Health</strong></td><td><code>respiratory_score</code></td><td>With every new daily payload</td><td>Oxygen saturation, respiratory rate (30-day baseline)</td></tr><tr><td>🏋️‍♀️ <strong>Training Stress</strong></td><td><code>total_stress_score</code></td><td>With every new daily payload</td><td>Sleep score, step count (7-day), activity duration in light / moderate / vigorous intensity zones</td></tr><tr><td>🏋️‍♂️ <strong>Training Stress V2</strong></td><td><code>total_stress_score_v2</code></td><td>With every new daily payload</td><td>Sleep score V2, step count (7-day), heart rate zones (7-day)</td></tr></tbody></table>

### Sleep payload

<table><thead><tr><th width="220">Score</th><th width="180">JSON field</th><th>Frequency</th><th>Source Data Needed</th></tr></thead><tbody><tr><td>💤 <strong>Sleep Score</strong></td><td><code>sleep_score</code></td><td>With every new sleep payload</td><td>Sleep stages (REM, deep, light, total), RHR, HRV, body temperature, SpO₂</td></tr><tr><td>💤 <strong>Sleep Score V2</strong></td><td><code>sleep_score_v2</code></td><td>With every new sleep payload</td><td>Sleep stages, average HR, body temperature, HRV (14-day baseline)</td></tr><tr><td>🌅 <strong>Readiness</strong></td><td><code>readiness_score</code></td><td>With every new sleep payload</td><td>Sleep stages, RHR (30-day), HRV (30-day), body temperature, respiratory rate, SpO₂</td></tr><tr><td>🫁 <strong>Respiratory Health V2</strong></td><td><code>respiratory_score_v2</code></td><td>With every new sleep payload</td><td>SpO₂, respiratory rate (14-day baseline)</td></tr></tbody></table>

### Activity payload

<table><thead><tr><th width="220">Score</th><th width="180">JSON field</th><th>Frequency</th><th>Source Data Needed</th></tr></thead><tbody><tr><td>🔥 <strong>Activity Strain</strong></td><td><code>strain_score</code></td><td>With every new activity payload</td><td>Average heart rate, activity duration, 14-day max HR</td></tr><tr><td>⚡ <strong>Activity Efficiency</strong></td><td><code>efficiency_score</code></td><td>With every new activity payload</td><td>Average speed, average heart rate, 14-day max HR</td></tr><tr><td>❤️ <strong>Activity RCRS</strong></td><td><code>rcrs_score</code></td><td>With every new activity payload</td><td>Average heart rate, activity duration, 30-day max HR</td></tr><tr><td>📈 <strong>Activity TRIMP</strong></td><td><code>trimp_score</code></td><td>With every new activity payload</td><td>Average heart rate, activity duration, 30-day max HR</td></tr></tbody></table>

> **Note**: Terra scores appear under the `data_enrichment` field inside each relevant payload (daily, sleep, or activity).

RHR, HRV, body temperature, and respiratory rate metrics are provided by most wearables if worn overnight during sleep.

***

## How to enable Health Scores

Some scores must be toggled on manually in the dashboard:

1. Log into your Terra Dashboard
2. Go to the **Health Scores** tab
3. Toggle the scores you want to receive to “Enabled”
4. Save settings

Enabled scores will then appear in the relevant payloads for users with eligible data.

{% prompt description="Enable health scores and read the values" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Enable the readiness and sleep_v2 scores in production and show me the latest values for user 8f2a1c.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

***

## How to receive Health Scores

You do **not** need to implement separate API calls, database logic, or webhook triggers to receive health scores. To receive Terra’s scores, the following conditions must be met:

1. **Active connection:** Your users have authorized their wearable (via Terra API). See Connect a User for specifics.
2. **Wearables sync necessary metrics:** The required metrics (e.g., HRV, respiratory rate, sleep stages) are available — see **Score Eligibility Criteria** below.
3. **The user wears the device (overnight):** Metrics like HRV, resting HR, and sleep stages depend on the user wearing the wearable during sleep.
4. **Baseline values are available:** The user has to wear their device for at least 4 days initially for our proprietary models to calibrate and generate baseline values. Some scores use longer baselines (14-day or 30-day) — those will continue to refine over time.
5. **Sufficient data is available:** After a user's baseline is established, the user has to wear their device at least once in the last 2 weeks.

If users are disconnected, you will not receive new data or scores.

***

## Score eligibility criteria

Terra’s health scores are automatically calculated only if sufficient data is available. The following input signals are required to ensure each score is accurate and meaningful.

If any of the **must-have metrics** are missing for a user on a given day, that score will not be generated or may return as `null`.

### Requirements per score

#### 💤 Sleep Score / 💤 Sleep Score V2

| Requirement          | Details                                                                 |
| -------------------- | ----------------------------------------------------------------------- |
| **Any sleep metric** | REM, deep sleep, light sleep, total duration                            |
| **Optional**         | HRV, resting heart rate, SpO₂, body temperature enhance score precision |

> At minimum, a valid sleep session with at least one stage or duration is required.

#### 🌅 Readiness

| Requirement              | Details                                                                                 |
| ------------------------ | --------------------------------------------------------------------------------------- |
| **Sleep stages and HRV** | Required REM, deep and total sleep, plus daily HRV (RMSSD or SDNN) with 30-day baseline |
| **Optional**             | RHR, body temperature, SpO₂, respiratory rate refine the score                          |

> Readiness requires at least \~3 hours of recorded sleep; sessions shorter than that produce a 0 sleep contributor.

#### 🫁 Respiratory Health / 🫁 Respiratory Health V2

| Requirement                   | Details                                                                     |
| ----------------------------- | --------------------------------------------------------------------------- |
| **SpO₂ and respiratory rate** | Blood oxygen saturation and respiratory rate measured in breaths per minute |
| **Optional**                  | Training activity to adjust score sensitivity post exercise                 |

> If SpO₂ or respiratory rate is missing, the respiratory health score will be null. V2 is computed on the sleep payload; the legacy version still appears on the daily payload.

#### 🏋️ Training Stress / 🏋️ Training Stress V2

| Requirement       | Details                                                                                                                                                                                                       |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **HRV and sleep** | Required daily HRV (e.g., RMSSD or SDNN) and a valid sleep score                                                                                                                                              |
| Optional          | Steps (7-day history) refine training calibration. Activity duration in light, moderate, and vigorous intensity zones (when provided by the wearable in the daily payload) sharpens the training-load signal. |

> If sleep data or HRV is missing, the training stress score will be null. If intensity-zone duration is not provided by the wearable, the training contributor falls back to zero rather than estimating from heart-rate samples.

#### 🛡️ Immunity Index

| Requirement                  | Details                                                                               |
| ---------------------------- | ------------------------------------------------------------------------------------- |
| **HRV and respiratory rate** | Required daily HRV (e.g., RMSSD or SDNN) and respiratory rate, with a 30-day baseline |
| **Optional**                 | Body temperature enhances score precision                                             |

> If HRV or respiratory rate data is missing, the immunity index will be null.

#### 💪🏻 Strain Index

| Requirement    | Details                                                                                          |
| -------------- | ------------------------------------------------------------------------------------------------ |
| **HRV and HR** | Required daily HRV (e.g., RMSSD or SDNN) and average heart rate, with 7-day and 28-day baselines |

> If HRV or HR data is missing, the strain index will be null.

#### 🌱 Resilience

| Requirement                | Details                                                                             |
| -------------------------- | ----------------------------------------------------------------------------------- |
| **HRV, RHR and resp rate** | Required daily HRV, resting heart rate, and respiratory rate, with 30-day baselines |
| **Optional**               | Body temperature and SpO₂ refine the score                                          |

> Resilience is generated once enough history exists to compute 30-day baselines for the must-have metrics.

#### 🔥 Activity Strain / ⚡ Activity Efficiency

| Requirement            | Details                                                                                      |
| ---------------------- | -------------------------------------------------------------------------------------------- |
| **HR during activity** | Activity must include average heart rate; HR range (max − min) must exceed 30 bpm            |
| **For Efficiency**     | Activity must additionally include average speed                                             |
| **Baseline**           | A 14-day rolling window of max HR is used; new users will see scores stabilize after 2 weeks |

> Activities without valid heart-rate data (e.g., flat-line HR or HR range below 30 bpm) will not produce a score.

#### ❤️ Activity RCRS / 📈 Activity TRIMP

| Requirement            | Details                                                                                        |
| ---------------------- | ---------------------------------------------------------------------------------------------- |
| **HR during activity** | Average heart rate and activity duration are required; HR range (max − min) must exceed 30 bpm |
| **Baseline**           | A 30-day rolling window of max HR is used                                                      |

> RCRS and TRIMP are physiological load metrics — they are not normalized to a 0–100 range, so values scale with workout intensity and duration.

***

## Understanding Health Score outputs

Each health score is generated using multiple physiological signals (e.g., HRV, sleep stages, respiration), which are transformed and combined using Terra’s proprietary models.

### 🔢 Score ranges

| Score                 | Range          | Interpretation                                                      |
| --------------------- | -------------- | ------------------------------------------------------------------- |
| Sleep Score           | 0–100          | Higher = better sleep quality                                       |
| Sleep Score V2        | 0–100          | Higher = better sleep quality (revised algorithm)                   |
| Readiness             | 0–100          | Higher = better readiness for the day                               |
| Respiratory Health    | 0–100          | Higher = better respiratory health                                  |
| Respiratory Health V2 | 0–100          | Higher = better respiratory health (revised algorithm)              |
| Training Stress       | 0–100          | Higher = higher signs of stress                                     |
| Training Stress V2    | 0–100          | Higher = higher signs of stress (revised algorithm)                 |
| Immunity Index        | 0–5            | Higher = weakened immunity                                          |
| Strain Index          | −50 to 50      | Positive = recovery, negative = strain (see traffic light)          |
| Resilience            | 0–100          | Higher = greater resilience and recovery capacity                   |
| Activity Strain       | 0–100          | Higher = more strain during the workout                             |
| Activity Efficiency   | 0–100          | Higher = better cardiovascular efficiency for the workout           |
| Activity RCRS         | 0+ (unbounded) | Relative cardiovascular response — scales with intensity × duration |
| Activity TRIMP        | 0+ (unbounded) | Training impulse — scales with intensity × duration                 |

### How to read contributor values

Each score has contributors, the underlying physiological metrics that influenced the score. These **do not reflect raw sensor values** (like BPM or °C). Instead, each contributor is:

* Normalized and scaled based on its contribution to the final score
* Weighted according to the model's proprietary algorithm, and adaptive to each individual’s baseline
* Transformed for interpretability and sensitivity

This allows a uniform scoring system across diverse devices and users.

#### Sleep Score Example

```json
"data_enrichment": {
  "sleep_contributors": {
    "rem": 40.34,
    "light": 100,
    "deep": 44.77,
    "total": 96.17,
    "rhr": 100,
    "hrv": 100,
    "temp": 100,
    "oxy": null
  },
  "sleep_score": 79.13
}
```

**Explanation:**

* `sleep_score`: Final normalized score (0–100)
* `sleep_contributors`: Each value is a transformed signal indicating how much that metric supports healthy sleep. 100 = strong positive influence.

> Note: If a contributor is null, the data was missing or not provided by the device.

#### Readiness Example

```json
"data_enrichment": {
  "readiness_contributors": {
    "sleep_score": 78.5,
    "hrv_score": 82.1,
    "rhr_score": 91.4,
    "temp_score": 100,
    "resp_score": 95.0,
    "oxy_score": 100
  },
  "readiness_score": 87.9
}
```

**Explanation:**

* `readiness_score`: Final normalized score (0–100). Higher = better recovery for the day.
* `readiness_contributors`: Six normalized inputs blended into the final score — sleep quality, HRV, resting HR, body temperature, respiratory rate, and SpO₂.

#### Immunity Index Example

```json
"data_enrichment": {
  "start_time": "2025-05-20T00:00:00.000000+01:00",
  "immune_contributors": {
    "hrv": 200,
    "respiration": 0,
    "temp": 0
  },
  "immune_index": 0.67
}
```

**Explanation:**

* `immune_index`: Value from **0 to 5**
  * `0` = No sign of immune system weakening
  * `5` = Strong signal of weakened immunity
* Contributor values like `hrv: 200` are **not raw HRV values**, but transformed indicators used by Terra’s model.

> A higher immune index means there are stronger biomarkers of physiological strain that may reflect a stressed or weakened immune system.

#### Strain Index Example

```json
"data_enrichment": {
  "start_time": "2025-05-20T00:00:00.000000+01:00",
  "strain_contributors": {
    "acute": 0.5,
    "momentum": -0.2,
    "z_slow": 1.3,
    "zcv": -0.8
  },
  "strain_index": 12.4,
  "strain_traffic_light": "GREEN"
}
```

**Explanation:**

* `strain_index`: Value from **−50 to 50**
  * `≥ 0` = Recovery and parasympathetic dominance (**GREEN**)
  * `−25` to `< 0` = Mild strain (**AMBER**)
  * `< −25` = Strong physiological strain (**RED**)
* `momentum`**:** 7-day trend of HRV vs HR
* `z_slow`**:** Deviation from 28-day baseline
* `zcv`**:** Stability or instability of HRV variability
* `acute`**:** Short-term (24h) HRV change

> The `strain_traffic_light` tag (“GREEN”, “AMBER”, “RED”) provides an easy-to-interpret summary derived from `strain_index`.

***

## Provider vs Terra scores

Several wearables (e.g., Oura, Fitbit) offer their own native scores. To avoid confusion:

* **Terra Scores** live under `data_enrichment` in the payload.
* **Provider Scores** (like "Stress" or "Sleep" scores) appear under the `scores` section but are **not generated by Terra**.

| Location          | Score Source      |
| ----------------- | ----------------- |
| `data_enrichment` | Terra             |
| `scores`          | Native device/app |

***


# Health Scores pricing

Health Scores is a paid add-on with a 14-day free trial. It does not use credits.

## The add-on

Health Scores adds adaptive scores to activity, daily and sleep data. It costs **$499/month** and starts with a **14-day free trial**. It does not use credits.

Activate it from the dashboard under **Settings → Plans & Pricing → Additional Products**. It is added on top of a base plan.

Without the add-on, health scores are not populated in activity, daily and sleep data.

See [Pricing](/unified-api/pricing) for the Quick Start plan and the other add-on products.


# Overview

Push structured workouts to your users' fitness devices and read their training calendar back.

The Planned Workouts API pushes structured training sessions to your users' fitness devices, so they don't have to build workouts by hand on their watch or bike computer. Your app can:

1. **Create reusable workout templates**: define the structure once.
2. **Schedule to any user**: apply athlete-specific parameters at scheduling time.
3. **Sync to the device**: the workout appears on the user's Garmin, COROS, Wahoo and other devices.
4. **Read the calendar back**: list a user's planned workouts, including ones a coach created on the provider's side.

Planned Workouts is a paid add-on to your Terra plan. See [Pricing](/planned-workouts-api/pricing).

## How it works

You create a template once, then schedule it to each athlete.

```
┌─────────────────────────────────────────────────────────────────┐
│  Phase 1: Create Template (once)                                │
│  POST /workouts                                                 │
│  → Returns workout_id                                           │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│  Phase 2: Schedule to User (per athlete)                        │
│  POST /workouts/{workout_id}/plan?user_id=X                     │
│  → Applies athlete's max HR, FTP, etc.                          │
│  → Pushes to user's connected device                            │
└─────────────────────────────────────────────────────────────────┘
```

## Supported providers

Terra pushes workouts to these providers:

| Provider      | Running | Cycling | Swimming | Strength |
| ------------- | ------- | ------- | -------- | -------- |
| Garmin        | ✓       | ✓       | ✓        | ✓        |
| COROS         | ✓       | ✓       | ✓        | ✓        |
| Wahoo         | ✓       | ✓       | —        | —        |
| Suunto        | ✓       | ✓       | ✓        | ✓        |
| TrainingPeaks | ✓       | ✓       | ✓        | ✓        |
| Huawei        | ✓       | —       | —        | —        |
| Zepp          | ✓       | ✓       | ✓        | —        |
| Hevy          | —       | —       | —        | ✓        |
| Apple         | ✓       | ✓       | ✓        | ✓        |

Intervals.icu is read only: Terra lists the workouts an athlete has planned there, but cannot push to it. Users connect it with their Intervals.icu API key on Terra's login screen.

Not all providers support all operations (update, retrieve, delete). See [Provider compatibility](/planned-workouts-api/provider-compatibility) for feature and operations support, including the **Retrieve** row for reading workouts back.

## Authentication

All requests require two headers:

| Header      | Description             |
| ----------- | ----------------------- |
| `dev-id`    | Your Terra developer ID |
| `x-api-key` | Your Terra API key      |

## Quickstart

{% prompt description="Create a workout template and schedule it to a device" icon="terminal" openInAIProviders="true" defaultExpanded="full" %}

```markdown
Create a 5x1km interval workout template and schedule it onto user 8f2a1c's Garmin for tomorrow.

Use the Terra CLI: brew install tryterra/tap/terra, or npm install -g @tryterra/cli, then terra login. Run terra docs ask --question "<question>" for anything you need from the Terra docs, and terra <command> --help for usage.
```

{% endprompt %}

### Create a workout template

Create a simple 20-minute interval run: 5min warmup → 3x(3min fast, 2min easy) → 5min cooldown.

```bash
curl -X POST "https://access.tryterra.co/api/v2/workouts" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "20min Interval Run",
    "sport": "running",
    "description": "Warmup, 3x intervals, cooldown",
    "step_blocks": [
      {
        "steps": [{
          "completion_condition": { "type": "time", "value": 300 },
          "intensity_type": "warmup"
        }]
      },
      {
        "completion_condition": { "type": "reps", "value": 3 },
        "steps": [
          {
            "completion_condition": { "type": "time", "value": 180 },
            "intensity_type": "active",
            "intensity_targets": [{
              "target_type": "heart_rate_max_percentage",
              "value_low": 85,
              "value_high": 90
            }]
          },
          {
            "completion_condition": { "type": "time", "value": 120 },
            "intensity_type": "rest"
          }
        ]
      },
      {
        "steps": [{
          "completion_condition": { "type": "time", "value": 300 },
          "intensity_type": "cooldown"
        }]
      }
    ]
  }'
```

Response:

```json
{
  "status": "success",
  "workout_id": "12345"
}
```

### Schedule it to a user

Push the workout to a specific user for tomorrow, with their max heart rate:

```bash
curl -X POST "https://access.tryterra.co/api/v2/workouts/12345/plan?user_id=USER_ID" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "planned_date": "2026-02-05",
    "max_heart_rate": 185
  }'
```

Response:

```json
{
  "status": "success",
  "planned_workout_id": "67890",
  "provider_workout_id": "abc123",
  "warnings": []
}
```

The workout now appears on the user's device. Providers that accept percentage targets, such as Garmin, receive 85-90% unchanged. Providers that need absolute values, such as Suunto and Zepp, receive 157-167 BPM, resolved from the max heart rate of 185 you passed. See [Athlete parameters](/planned-workouts-api/athlete-parameters).

### List the user's planned workouts

```bash
curl -X GET "https://access.tryterra.co/api/v2/plannedWorkouts?user_id=USER_ID&start_date=2026-02-05&end_date=2026-02-12" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY"
```

Response (abbreviated):

```json
[
  {
    "planned_workout_id": "67890",
    "workout_id": "12345",
    "planned_date": "2026-02-05",
    "provider_workout_id": "abc123",
    "is_external": false,
    "warnings": [],
    "workout": {
      "name": "20min Interval Run",
      "sport": "running",
      "step_blocks": [
        {
          "steps": [
            {
              "completion_condition": { "type": "time", "value": 300 },
              "intensity_type": "warmup"
            }
          ]
        }
      ]
    }
  }
]
```

The list also holds workouts created on the provider's side. See [Read scheduled workouts](#read-scheduled-workouts) for the response shape, the date window and the provider read headers.

## API endpoints

| Method | Endpoint                          | Description                                                       |
| ------ | --------------------------------- | ----------------------------------------------------------------- |
| POST   | `/workouts`                       | Create workout template                                           |
| GET    | `/workouts`                       | List all templates                                                |
| GET    | `/workouts/{id}`                  | Get template details                                              |
| PUT    | `/workouts/{id}`                  | Update template and re-send it to upcoming planned workouts       |
| DELETE | `/workouts/{id}`                  | Delete template                                                   |
| POST   | `/workouts/{id}/plan?user_id=X`   | Schedule workout to user                                          |
| GET    | `/plannedWorkouts/{id}`           | Get a planned workout created through Terra                       |
| GET    | `/plannedWorkouts?user_id=X`      | List Terra-created and provider-created workouts (dates optional) |
| PATCH  | `/plannedWorkouts/{id}?user_id=X` | Update scheduled date (only `planned_date`, not athlete params)   |
| DELETE | `/plannedWorkouts/{id}?user_id=X` | Remove scheduled workout                                          |

A template's `estimated_tss`, `estimated_intensity_factor`, `estimated_distance_meters` and `estimated_calories` are forwarded to TrainingPeaks when you plan or reschedule the workout. TrainingPeaks ignores TSS, intensity factor and duration whenever any step target is something other than RPE: it derives them from the athlete's own thresholds instead, and Terra returns warnings on `workout.estimated_tss`, `workout.estimated_intensity_factor` and `workout.estimated_duration_seconds`. `POST /workouts` rejects an `estimated_tss` outside 0 to 9999 and an `estimated_intensity_factor` outside 0 to 5.

## Update a workout template

`PUT /workouts/{id}` takes the same body as `POST /workouts` and replaces the whole template. Fields you leave out are cleared, so send the full template even to change one field.

Terra then re-sends the new version to every upcoming planned workout made from this template. Each keeps its `planned_date` and athlete parameters. The response lists every planned workout:

```json
{
  "status": "success",
  "workout_id": "1024",
  "planned_workouts": [
    {
      "planned_workout_id": "2048",
      "provider_workout_id": "981230",
      "status": "updated"
    }
  ]
}
```

| Status    | Meaning                                                                                                                                                             |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `updated` | The provider has the new version. `warnings` lists anything it could not take, as when planning. `provider_workout_id` changes if the provider assigned a new one.  |
| `failed`  | The provider rejected it, and `error` has the reason. Repeat the request to re-send.                                                                                |
| `skipped` | Nothing was sent: the planned workout is completed or in the past, it isn't on a device yet, or the user's connection no longer allows it (they need to reconnect). |

If any planned workout failed, the response is `207 Multi-Status`, with a `message` in place of `status`. The template is already saved.

* **Upcoming** means a `planned_date` of today or later (UTC) that isn't completed. Past and completed planned workouts keep the version they were sent.
* **Apple Health:** a planned workout already on the device is told to fetch the new version. One not synced yet picks it up when it syncs.
* **Pricing:** each planned workout re-sent costs 10 credits, like a reschedule. Skipped and failed ones are free. See [Pricing](/planned-workouts-api/pricing).
* **Limit:** a template with more than 50 planned workouts, counting past and completed ones, returns `422 Unprocessable Entity` and nothing changes. Create a new template instead.
* **Concurrent changes:** while one request is changing a template, other requests that update, delete or plan it, or reschedule or delete its planned workouts, return `409 Conflict`. Retry after a short wait.

{% hint style="warning" %}
Deleting a workout template also deletes every workout scheduled from it. When you call `DELETE /workouts/{id}`, Terra removes all planned workouts linked to that template from every connected provider (e.g. Garmin, Suunto, Wahoo) before deleting the template itself. This cannot be undone. To unschedule a workout for one user, use `DELETE /plannedWorkouts/{id}` instead.
{% endhint %}

## Read scheduled workouts

`GET /plannedWorkouts?user_id=X` returns everything on the user's calendar, from both origins, in one shape. Every item carries the workout body under `workout` (name, sport, `step_blocks`, estimates), plus `planned_date`, `provider_workout_id` and `warnings`:

* **Workouts you scheduled through Terra**: identified by a `planned_workout_id`. Use it with the `GET`/`PATCH`/`DELETE /plannedWorkouts/{id}` endpoints. The workout body is inline under `workout` and `workout_id` names the template it was planned from.
* **Workouts created on the provider's side** (e.g. by a coach on TrainingPeaks): marked `is_external: true`. These are read live from the provider and are read-only. `planned_workout_id` and `workout_id` are null, so they cannot be addressed by id or updated or deleted through Terra. The body arrives under `workout` like every other item: title, sport, structured steps with targets, and planned estimates such as `estimated_duration_seconds`, `estimated_tss` and `estimated_intensity_factor`. Use `provider_workout_id` as their stable identifier; a completed workout's activity carries the same id in `summary_id`.

Provider-created workouts are listed for Garmin, Wahoo, Suunto, TrainingPeaks and Intervals.icu. Garmin returns only the workouts your app created. Intervals.icu is read-only for planned workouts: you can list what the athlete has planned there, but you cannot push to it. COROS, Zepp, Huawei and Apple have no way to read a calendar back, and Hevy has no calendar (a workout pushed to Hevy becomes a library routine and carries no date), so for those providers the list contains only the workouts you scheduled through Terra. A workout you pushed through Terra that the provider echoes back is listed once, as the Terra row.

```json
{
  "planned_workout_id": null,
  "workout_id": null,
  "planned_date": "2026-07-15",
  "provider_workout_id": "3841172642",
  "is_external": true,
  "created_at": null,
  "last_updated_at": null,
  "athlete_metrics": null,
  "warnings": [],
  "workout": {
    "name": "threshold",
    "sport": "cycling",
    "estimated_duration_seconds": 3816,
    "estimated_tss": 65.4,
    "estimated_intensity_factor": 0.75,
    "step_blocks": [
      {
        "completion_condition": null,
        "steps": [
          {
            "intensity_type": "warmup",
            "completion_condition": { "type": "time", "value": 900 },
            "intensity_targets": [
              { "target_type": "heart_rate_max_percentage", "value_low": 40, "value_high": 50 }
            ],
            "notes": "Warm up"
          }
        ]
      }
    ]
  }
}
```

Items also carry `coercion_warnings` and `details`, the older forms of `warnings` and `workout`. Both are deprecated: read `warnings` and `workout`, which use the same field names and values as `GET /workouts/{workout_id}`.

Two response headers report the live provider read:

| Header                            | Values                                                                              |
| --------------------------------- | ----------------------------------------------------------------------------------- |
| `X-Terra-Provider-Fetch`          | `ok`, `skipped`, `rate_limited`, `unauthorized`, `unavailable`, `timeout`, `failed` |
| `X-Terra-Provider-Data-Truncated` | `true` when provider-side workouts could not be included                            |

`skipped` means the provider does not expose planned workouts. Anything other than `ok` also sets `X-Terra-Provider-Data-Truncated: true`. The call still returns `200` with the workouts Terra has stored, so check the headers before treating a short list as an empty calendar.

`warnings` is an array of `{path, message}` entries describing what had to change between your template and the provider's format: on workouts you pushed, what the push adjusted; on provider-created workouts, what reading them back adjusted. See [Coercion warnings](/planned-workouts-api/coercion-warnings).

{% hint style="info" %}
Pass a date window to see upcoming workouts. Without `start_date`/`end_date`, provider-side workouts default to the **trailing 30 days**, so upcoming ones will not appear. Workouts you scheduled through Terra are not windowed when the dates are omitted. Pass an explicit window (e.g. today through next week) to list what is ahead: both bounds are planned dates and both are inclusive. Some providers also limit how far ahead they expose planned workouts.

A planned workout the user has **completed** leaves this list and is delivered as a completed activity instead.
{% endhint %}

## Next steps

* [Pricing](/planned-workouts-api/pricing): add-on cost, credits, and what works without it
* [Core concepts](/planned-workouts-api/core-concepts): workout structure, blocks, steps and targets
* [Sport-specific examples](/planned-workouts-api/sport-specific-examples): running, cycling, swimming and strength
* [Athlete parameters](/planned-workouts-api/athlete-parameters): personalize workouts per user
* [Provider compatibility](/planned-workouts-api/provider-compatibility): what works where
* [Coercion warnings](/planned-workouts-api/coercion-warnings): handle feature limitations
* [Exercise reference](/planned-workouts-api/exercise-reference): exercise names and how they map across providers
* [Garmin and Hevy exercise reference](/planned-workouts-api/garmin-exercise-reference): provider exercise catalogs


# Pricing

Planned Workouts is a paid add-on to your Terra plan, with usage measured in Planned Workouts credits.

## The add-on

Planned Workouts is available as an add-on to any Terra base plan for **$99/month**. Activate it from the dashboard, either on the Planned Workouts page itself or under **Settings → Plans & Pricing → Additional Products**.

Without the add-on active, every Planned Workouts REST endpoint returns `403 Forbidden` except deletes. You can still delete workout templates and planned workouts you created earlier.

## Credits

Usage is measured in **Planned Workouts credits**, a separate balance from your Unified API credits. Your subscription includes **20,000 Planned Workouts credits per month**. Beyond that, they are billed at **$0.005 each** (10 Planned Workouts credits = $0.05) at the end of each billing cycle, and **$0.003 each** past 1,000,000 in a month.

| Action                                                                                                                                 | Planned Workouts credits                         |
| -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| **Push**: `POST /workouts/{workout_id}/plan` (sync a workout to a user's calendar)                                                     | 10 credits ($0.05)                               |
| **Push**: `PATCH /plannedWorkouts/{planned_workout_id}` (reschedule, re-syncs to the provider)                                         | 10 credits ($0.05)                               |
| **Push**: `PUT /workouts/{workout_id}` (update a template, re-sends each upcoming planned workout)                                     | 10 credits ($0.05) per `updated` planned workout |
| **Push**: `POST /routes/{route_id}/push` (send a [route](/routes-api/overview) to a user's device)                                     | 10 credits ($0.05)                               |
| **Push**: `PUT /routes/{route_id}` (update a route, re-sends each pushed route)                                                        | 10 credits ($0.05) per `updated` pushed route    |
| **Push** (legacy): `POST /v2/plannedWorkout`                                                                                           | 10 credits per workout in `data`                 |
| **Pull**: `GET /plannedWorkouts?user_id=...` (one live read of the user's calendar, including workouts created on the provider's side) | 1 credit per request                             |
| Reads of Terra-stored workouts and routes, deletes, creating and reading templates, SDK sync polling                                   | Free                                             |

The 20,000 included Planned Workouts credits cover 2,000 pushes per month, or any mix of pushes and pulls.

Which of the two you can use depends on the provider. Intervals.icu is read-only for planned workouts, so an Intervals.icu connection only ever spends Planned Workouts credits on pulls. See [Provider compatibility](/planned-workouts-api/provider-compatibility) for what each provider supports.

{% hint style="info" %}
Only successful operations are billed. A push the provider rejects costs nothing. A pull is billed once the live provider read completes. If the provider cannot be read, the response still returns your Terra-scheduled workouts with `X-Terra-Provider-Data-Truncated: true` and is free.
{% endhint %}


# Core concepts

### Workout Structure

A workout template is a hierarchy of blocks and steps:

```
WorkoutTemplate
├── name: "FTP Intervals"
├── sport: "cycling"
├── environment: "outdoor" (optional: indoor, outdoor, pool)
├── description: "Build threshold power"
├── pool_length_meters: null (only for swimming)
├── estimated_duration_seconds: 1800 (optional)
├── estimated_distance_meters: null (optional)
├── estimated_calories: null (optional)
├── estimated_tss: null (optional, 0-9999)
├── estimated_intensity_factor: null (optional, 0-5)
│
└── step_blocks: [
      StepBlock {
        completion_condition: { type: "reps", value: 4 }  ← Repeat 4 times
        steps: [
          WorkoutStep { ... },  ← Do this
          WorkoutStep { ... }   ← Then this
        ]
      }
    ]
```

### Step Blocks

A step block groups one or more steps that execute together. The block's `completion_condition` controls repetition:

| Block Completion                        | Behavior                      |
| --------------------------------------- | ----------------------------- |
| `{ "type": "reps", "value": 4 }`        | Repeat all steps 4 times      |
| `{ "type": "time", "value": 1200 }`     | Repeat until 20 minutes total |
| `{ "type": "distance", "value": 5000 }` | Repeat until 5km total        |
| `{ "type": "open" }` or omitted         | Execute once (no repeat)      |

#### Example: 4x400m Intervals

```json
{
  "step_blocks": [{
    "completion_condition": { "type": "reps", "value": 4 },
    "steps": [
      {
        "completion_condition": { "type": "distance", "value": 400 },
        "intensity_type": "active"
      },
      {
        "completion_condition": { "type": "distance", "value": 200 },
        "intensity_type": "rest"
      }
    ]
  }]
}
```

This creates: 400m fast → 200m easy → 400m fast → 200m easy → 400m fast → 200m easy → 400m fast → 200m easy

### Workout Steps

Each step defines:

| Field                  | Required | Description                                                      |
| ---------------------- | -------- | ---------------------------------------------------------------- |
| `completion_condition` | Yes      | When this step ends                                              |
| `intensity_type`       | Yes      | How hard (warmup/active/rest/recovery/cooldown)                  |
| `intensity_targets`    | No       | Target metrics (HR, power, pace, etc.)                           |
| `notes`                | No       | Text shown to athlete                                            |
| `controls`             | No       | Equipment settings held during the step: `grade` or `resistance` |
| `strength`             | No       | Exercise details for strength training                           |
| `swimming`             | No       | Stroke/equipment for swimming                                    |

### Completion Conditions

How a step (or block) ends:

| Type                 | Value   | Description                                |
| -------------------- | ------- | ------------------------------------------ |
| `time`               | Seconds | End after duration (e.g., 300 = 5 minutes) |
| `distance`           | Meters  | End after distance (e.g., 1000 = 1km)      |
| `reps`               | Count   | End after N repetitions                    |
| `calories`           | kcal    | End after calories burned                  |
| `open`               | —       | Manual end (lap button)                    |
| `hr_less_than`       | BPM     | End when HR drops below                    |
| `hr_greater_than`    | BPM     | End when HR rises above                    |
| `power_less_than`    | Watts   | End when power drops below                 |
| `power_greater_than` | Watts   | End when power rises above                 |

#### Example: Recovery Until HR Drops

```json
{
  "completion_condition": {
    "type": "hr_less_than",
    "value": 120
  },
  "intensity_type": "rest"
}
```

### Intensity Types

| Type       | Display         | Use For                       |
| ---------- | --------------- | ----------------------------- |
| `warmup`   | Warmup          | Gradual start                 |
| `active`   | Work / Interval | Main effort                   |
| `rest`     | Rest            | Full stop between intervals   |
| `recovery` | Recovery        | Easy effort between intervals |
| `cooldown` | Cooldown        | Gradual end                   |

### Intensity Targets

Targets define the goal metric for a step. You can have multiple targets per step (provider-dependent).

#### Target Types

**Absolute Targets:**

| Target Type  | Value Unit | Example                       | Provider Support                       |
| ------------ | ---------- | ----------------------------- | -------------------------------------- |
| `heart_rate` | BPM        | 150-160 BPM                   | All except Hevy                        |
| `power`      | Watts      | 250-280W                      | All except Huawei and Hevy             |
| `speed`      | m/s        | 4.0-4.5 m/s                   | All except Hevy                        |
| `pace`       | sec/km     | 270-300 sec/km (4:30-5:00/km) | All except Hevy                        |
| `cadence`    | rpm or spm | 170-180 spm                   | All except Hevy (Zepp: secondary only) |
| `rpe`        | 1-10       | 7-8 RPE                       | Wahoo, TrainingPeaks only              |

{% hint style="warning" %}
Pace is in seconds per kilometre for every sport, swimming included: 4:30/km is `270`, not `4.5`, and 1:30 per 100 m is `900`, not `90`.
{% endhint %}

**Percentage Targets** (require athlete parameters at scheduling):

| Target Type                       | Requires               | Example                   |
| --------------------------------- | ---------------------- | ------------------------- |
| `heart_rate_max_percentage`       | `max_heart_rate`       | 80-85% of max HR          |
| `heart_rate_threshold_percentage` | `threshold_heart_rate` | 95-100% of threshold      |
| `power_percentage`                | `ftp`                  | 90-95% of FTP             |
| `speed_percentage`                | `threshold_speed`      | 85-90% of threshold speed |

**Zone Targets** (device-configured zones):

| Target Type       | Value | Provider Support                                                                                                            |
| ----------------- | ----- | --------------------------------------------------------------------------------------------------------------------------- |
| `heart_rate_zone` | 1-5   | All except Hevy (Garmin native, others convert to BPM or %). Uses threshold HR (COROS, Zepp) or max HR (others) as baseline |
| `power_zone`      | 1-7   | All except Huawei and Hevy (Garmin native, others convert to % FTP or watts)                                                |

#### Target Value Formats

Targets support single values or ranges. Percentage targets (`heart_rate_max_percentage`, `heart_rate_threshold_percentage`, `power_percentage`, `speed_percentage`) must use `value_low` and/or `value_high`: an exact `value` is rejected with a 400. Expanding a single value into a range also returns a coercion warning.

```json
// Range (recommended)
{
  "target_type": "power_percentage",
  "value_low": 90,
  "value_high": 95
}

// Single value (Terra expands to ±5% range automatically, except RPE which stays as a point value)
{
  "target_type": "heart_rate",
  "value": 155
}
```

### Sport Types

| Sport                | Description               | Provider Support                                  |
| -------------------- | ------------------------- | ------------------------------------------------- |
| `running`            | Running                   | All except Hevy                                   |
| `cycling`            | Cycling                   | All except Huawei and Hevy                        |
| `swimming`           | Swimming                  | Garmin, COROS, Suunto, TrainingPeaks, Zepp, Apple |
| `strength`           | Weight training           | Garmin, COROS, Suunto, TrainingPeaks, Apple, Hevy |
| `rowing`             | Rowing                    | TrainingPeaks, Apple                              |
| `yoga`               | Yoga                      | Garmin, Apple                                     |
| `pilates`            | Pilates                   | Garmin only                                       |
| `cardio`             | General cardio            | Garmin only                                       |
| `trail_running`      | Trail running             | Garmin, COROS, Wahoo, Suunto, Zepp                |
| `mountain_biking`    | Mountain biking           | Garmin, Wahoo, Suunto, TrainingPeaks              |
| `backcountry_skiing` | Backcountry / ski touring | Garmin, Suunto                                    |
| `hiking`             | Hiking                    | Garmin, Suunto                                    |
| `walking`            | Walking                   | Garmin, Suunto, TrainingPeaks                     |
| `elliptical`         | Elliptical                | Garmin                                            |
| `stair_climbing`     | Stair climbing            | None native, coerced with a warning               |

Unsupported sport types are coerced to the provider's closest equivalent with a coercion warning. See [Provider Compatibility](/planned-workouts-api/provider-compatibility) for details.

### Environment (Optional)

Use the `environment` field to distinguish indoor/outdoor variants:

| Environment | Description                               |
| ----------- | ----------------------------------------- |
| `indoor`    | Indoor (treadmill, stationary bike, etc.) |
| `outdoor`   | Outdoor                                   |
| `pool`      | Pool swimming                             |

If omitted, the provider uses its default. Examples:

```json
{ "sport": "running", "environment": "indoor" }    // Treadmill
{ "sport": "cycling", "environment": "indoor" }    // Stationary bike
{ "sport": "swimming", "environment": "pool" }     // Lap swimming
{ "sport": "swimming", "environment": "outdoor" }  // Open water swimming
{ "sport": "running" }                              // Default (outdoor)
```

### Workout Estimates (Optional)

Estimates describe the workout as a whole, not a single step. All five are optional.

| Field                        | Unit    | Notes                         |
| ---------------------------- | ------- | ----------------------------- |
| `estimated_duration_seconds` | Seconds | Planned total time            |
| `estimated_distance_meters`  | Meters  | Planned total distance        |
| `estimated_calories`         | kcal    | Planned energy                |
| `estimated_tss`              | 0-9999  | Planned Training Stress Score |
| `estimated_intensity_factor` | 0-5     | Planned Intensity Factor      |

Terra forwards all five to TrainingPeaks when the workout is scheduled or rescheduled, and returns them on workouts read back from any provider that exposes them.

TrainingPeaks derives TSS, Intensity Factor and duration from the athlete's own thresholds whenever any step target is not RPE. Your values are ignored in that case, and Terra returns coercion warnings on `workout.estimated_tss`, `workout.estimated_intensity_factor` and `workout.estimated_duration_seconds`. Distance and calories are always forwarded.

An `estimated_tss` outside 0-9999, or an `estimated_intensity_factor` outside 0-5, is rejected when the template is created.

### Complete Example

A 30-minute cycling workout with warmup, FTP intervals, and cooldown:

```json
{
  "name": "30min FTP Builder",
  "sport": "cycling",
  "description": "4x4min @ 95-100% FTP with 2min recovery",
  "step_blocks": [
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 300 },
        "intensity_type": "warmup",
        "intensity_targets": [{
          "target_type": "power_percentage",
          "value_low": 50,
          "value_high": 60
        }]
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 4 },
      "steps": [
        {
          "completion_condition": { "type": "time", "value": 240 },
          "intensity_type": "active",
          "intensity_targets": [{
            "target_type": "power_percentage",
            "value_low": 95,
            "value_high": 100
          }]
        },
        {
          "completion_condition": { "type": "time", "value": 120 },
          "intensity_type": "rest",
          "intensity_targets": [{
            "target_type": "power_percentage",
            "value_low": 40,
            "value_high": 50
          }]
        }
      ]
    },
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 300 },
        "intensity_type": "cooldown",
        "intensity_targets": [{
          "target_type": "power_percentage",
          "value_low": 40,
          "value_high": 50
        }]
      }]
    }
  ]
}
```

### Reading Workouts Back

`GET /plannedWorkouts?user_id=X` returns this same structure. Every item carries the workout body under `workout`: name, sport, `step_blocks` and estimates, whether you scheduled it through Terra or the athlete created it on the provider.

Provider-created workouts are marked `is_external: true`, have no `workout_id`, and are listed for Garmin, Wahoo, Suunto, TrainingPeaks and Intervals.icu. Their `sport` is `unspecified` when the provider's sport has no Terra equivalent. `warnings` lists anything that could not be represented exactly when the provider's workout was read into this structure. Repeat blocks are preserved.

Intervals.icu is read-only for planned workouts: workouts created there are listed, but Terra cannot push workouts to it.

Without `start_date` and `end_date`, provider-created workouts default to the trailing 30 days. Pass an explicit window to list upcoming workouts. When the provider cannot be read the response is still a 200 carrying the workouts Terra scheduled, with `X-Terra-Provider-Data-Truncated: true` and `X-Terra-Provider-Fetch` giving the reason.

### Validation Rules

Templates are validated when created. Key rules:

| Field                        | Requirement                                                                                                                        |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `name`                       | Required, non-empty                                                                                                                |
| `sport`                      | Required, must be a valid sport type                                                                                               |
| `step_blocks`                | At least one block required                                                                                                        |
| Each block                   | At least one step required                                                                                                         |
| Each step                    | `intensity_type` required (`warmup`, `active`, `rest`, `recovery`, `cooldown`)                                                     |
| Each step                    | `completion_condition` defaults to `open` if omitted                                                                               |
| `pool_length_meters`         | Only allowed for swimming workouts                                                                                                 |
| `value_low` / `value_high`   | Cannot use both `value` and `value_low`/`value_high` on the same target                                                            |
| Range targets                | `value_low` must be strictly less than `value_high`                                                                                |
| Athlete metrics              | All values must be positive if provided (`ftp`, `max_heart_rate`, `threshold_heart_rate`, `threshold_speed`, `pool_length_meters`) |
| `planned_date`               | Format: `YYYY-MM-DD`                                                                                                               |
| `estimated_tss`              | Between 0 and 9999 if provided                                                                                                     |
| `estimated_intensity_factor` | Between 0 and 5 if provided                                                                                                        |
| Percentage targets           | Must use `value_low` and/or `value_high`, not `value`                                                                              |

**Target value sanity checks.** A value outside these ranges is rejected with a 400 when the template is created:

| Target Type        | Valid Range |
| ------------------ | ----------- |
| Heart rate (BPM)   | 30–250      |
| Power (watts)      | 1–2000      |
| Speed (m/s)        | 0–15        |
| Pace (sec/km)      | 1–7200      |
| Cadence (rpm/spm)  | 1–300       |
| RPE                | 1–10        |
| Percentage targets | 0–200%      |


# Sport-specific examples

Complete, copy-paste examples for each sport type.

### Running

#### Interval Run with HR Targets

5min warmup → 5x(3min @ 85-90% max HR, 2min easy) → 5min cooldown

```json
{
  "name": "5x3min HR Intervals",
  "sport": "running",
  "step_blocks": [
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 300 },
        "intensity_type": "warmup"
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 5 },
      "steps": [
        {
          "completion_condition": { "type": "time", "value": 180 },
          "intensity_type": "active",
          "intensity_targets": [{
            "target_type": "heart_rate_max_percentage",
            "value_low": 85,
            "value_high": 90
          }]
        },
        {
          "completion_condition": { "type": "time", "value": 120 },
          "intensity_type": "rest"
        }
      ]
    },
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 300 },
        "intensity_type": "cooldown"
      }]
    }
  ]
}
```

Schedule with: `POST /workouts/{workout_id}/plan?user_id=X` body: `{ "planned_date": "2026-02-10", "max_heart_rate": 185 }`

#### Tempo Run with Pace Target

20min @ 4:30-4:45/km pace (270-285 sec/km)

```json
{
  "name": "20min Tempo",
  "sport": "running",
  "step_blocks": [
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 300 },
        "intensity_type": "warmup"
      }]
    },
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 1200 },
        "intensity_type": "active",
        "intensity_targets": [{
          "target_type": "pace",
          "value_low": 270,
          "value_high": 285
        }]
      }]
    },
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 300 },
        "intensity_type": "cooldown"
      }]
    }
  ]
}
```

***

### Cycling

#### FTP Intervals

4x8min @ 95-100% FTP with 4min recovery

```json
{
  "name": "4x8min FTP",
  "sport": "cycling",
  "step_blocks": [
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 600 },
        "intensity_type": "warmup",
        "intensity_targets": [{
          "target_type": "power_percentage",
          "value_low": 50,
          "value_high": 60
        }]
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 4 },
      "steps": [
        {
          "completion_condition": { "type": "time", "value": 480 },
          "intensity_type": "active",
          "intensity_targets": [{
            "target_type": "power_percentage",
            "value_low": 95,
            "value_high": 100
          }]
        },
        {
          "completion_condition": { "type": "time", "value": 240 },
          "intensity_type": "rest",
          "intensity_targets": [{
            "target_type": "power_percentage",
            "value_low": 40,
            "value_high": 50
          }]
        }
      ]
    },
    {
      "steps": [{
        "completion_condition": { "type": "time", "value": 600 },
        "intensity_type": "cooldown"
      }]
    }
  ]
}
```

Schedule with: `POST /workouts/{workout_id}/plan?user_id=X` body: `{ "planned_date": "2026-02-10", "ftp": 280 }`

#### Indoor Cycling with Cadence

Stationary bike workout with cadence targets

```json
{
  "name": "Cadence Drills",
  "sport": "cycling",
  "environment": "indoor",
  "step_blocks": [
    {
      "completion_condition": { "type": "reps", "value": 3 },
      "steps": [
        {
          "completion_condition": { "type": "time", "value": 120 },
          "intensity_type": "active",
          "intensity_targets": [
            {
              "target_type": "power_percentage",
              "value_low": 70,
              "value_high": 80
            },
            {
              "target_type": "cadence",
              "value_low": 100,
              "value_high": 110
            }
          ],
          "notes": "High cadence"
        },
        {
          "completion_condition": { "type": "time", "value": 120 },
          "intensity_type": "active",
          "intensity_targets": [
            {
              "target_type": "power_percentage",
              "value_low": 70,
              "value_high": 80
            },
            {
              "target_type": "cadence",
              "value_low": 60,
              "value_high": 70
            }
          ],
          "notes": "Low cadence / strength"
        }
      ]
    }
  ]
}
```

***

### Swimming

#### Lap Swimming with Strokes

Pool workout with stroke-specific intervals

```json
{
  "name": "Mixed Stroke Workout",
  "sport": "swimming",
  "environment": "pool",
  "pool_length_meters": 25,
  "step_blocks": [
    {
      "steps": [{
        "completion_condition": { "type": "distance", "value": 200 },
        "intensity_type": "warmup",
        "swimming": { "stroke_type": "freestyle" }
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 4 },
      "steps": [
        {
          "completion_condition": { "type": "distance", "value": 50 },
          "intensity_type": "active",
          "swimming": { "stroke_type": "butterfly" }
        },
        {
          "completion_condition": { "type": "distance", "value": 50 },
          "intensity_type": "rest",
          "swimming": { "stroke_type": "backstroke" }
        }
      ]
    },
    {
      "steps": [{
        "completion_condition": { "type": "distance", "value": 200 },
        "intensity_type": "cooldown",
        "swimming": { "stroke_type": "freestyle" }
      }]
    }
  ]
}
```

#### Swimming with a Pace Target

Swim pace is in seconds per kilometre, like every other sport: 1:30-1:40 per 100 m is `900`-`1000`.

```json
{
  "completion_condition": { "type": "distance", "value": 100 },
  "intensity_type": "active",
  "intensity_targets": [{ "target_type": "pace", "value_low": 900, "value_high": 1000 }],
  "swimming": { "stroke_type": "freestyle" }
}
```

#### Swimming with Equipment

```json
{
  "completion_condition": { "type": "distance", "value": 100 },
  "intensity_type": "active",
  "swimming": {
    "stroke_type": "freestyle",
    "equipment": ["swim_paddles"]
  }
}
```

Providers that support equipment take one item per step. If you send more, the first is used and Terra returns a coercion warning for the rest.

**Available strokes:** `freestyle`, `backstroke`, `breaststroke`, `butterfly`, `mixed`, `drill`, `im`

**Available equipment:** `swim_kickboard`, `swim_paddles`, `swim_pull_buoy`, `swim_fins`, `swim_snorkel`

***

### Strength Training

#### Basic Strength Workout

3 sets of 3 exercises

```json
{
  "name": "Upper Body",
  "sport": "strength",
  "step_blocks": [
    {
      "completion_condition": { "type": "reps", "value": 3 },
      "steps": [{
        "completion_condition": { "type": "reps", "value": 10 },
        "intensity_type": "active",
        "notes": "Bench Press",
        "strength": {
          "exercise_name": "BARBELL_BENCH_PRESS",
          "weight": 60,
          "weight_display_unit": "kg"
        }
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 3 },
      "steps": [{
        "completion_condition": { "type": "reps", "value": 12 },
        "intensity_type": "active",
        "notes": "Rows",
        "strength": {
          "exercise_name": "BENT_OVER_ROW_WITH_BARBELL",
          "weight": 50,
          "weight_display_unit": "kg"
        }
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 3 },
      "steps": [{
        "completion_condition": { "type": "reps", "value": 10 },
        "intensity_type": "active",
        "notes": "Shoulder Press",
        "strength": {
          "exercise_name": "OVERHEAD_PRESS",
          "weight": 40,
          "weight_display_unit": "kg"
        }
      }]
    }
  ]
}
```

#### Exercise Name Flexibility

Garmin exercise names are flexible:

```json
// All of these work:
{ "exercise_name": "BARBELL_BENCH_PRESS" }
{ "exercise_name": "barbell_bench_press" }
{ "exercise_name": "Barbell Bench Press" }
{ "exercise_name": "barbell bench press" }
```

See Exercise Reference for full list.

***

### Multi-Sport (Triathlon)

For triathlon or brick workouts, create separate templates for each sport and schedule them on the same day:

```bash
# Bike portion (use the workout_id returned by POST /workouts)
POST /workouts/12345/plan?user_id=USER_ID
{ "planned_date": "2026-02-10", "ftp": 250 }

# Run portion
POST /workouts/12346/plan?user_id=USER_ID
{ "planned_date": "2026-02-10", "max_heart_rate": 180 }
```


# Athlete parameters

Personalize a workout template for each athlete with max heart rate, threshold heart rate, FTP, threshold speed and pool length.

### Overview

Athlete parameters are provided when scheduling a workout to a specific user. They give Terra the baseline it needs to express your targets on each provider: percentage targets become absolute values where the provider only accepts absolute numbers, and absolute heart rate and power targets become percentages on TrainingPeaks.

**Key concept:** Templates are generic. Athlete parameters are applied at scheduling time.

Athlete parameters apply only to workouts you schedule through Terra. Workouts created on the provider side, returned by `GET /plannedWorkouts` with `is_external: true`, already carry the provider's own targets and are not personalised. Intervals.icu is read only for planned workouts, so it takes no scheduled workouts and no athlete parameters.

### Parameters

| Parameter              | Unit   | Used By                                   |
| ---------------------- | ------ | ----------------------------------------- |
| `max_heart_rate`       | BPM    | `heart_rate_max_percentage` targets       |
| `threshold_heart_rate` | BPM    | `heart_rate_threshold_percentage` targets |
| `ftp`                  | Watts  | `power_percentage` targets                |
| `threshold_speed`      | m/s    | `speed_percentage` targets                |
| `pool_length_meters`   | Meters | Swimming workouts (overrides template)    |

### When parameters are required

| Target Type                       | Required Parameter     | What Happens Without It                                                                                      |
| --------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------ |
| `heart_rate_max_percentage`       | `max_heart_rate`       | Falls back to 190 BPM, with a coercion warning                                                               |
| `heart_rate_threshold_percentage` | `threshold_heart_rate` | Falls back to 170 BPM, with a coercion warning                                                               |
| `power_percentage`                | `ftp`                  | Falls back to 200 W, with a coercion warning                                                                 |
| `speed_percentage`                | `threshold_speed`      | Falls back to 3.33 m/s, with a coercion warning                                                              |
| `heart_rate` (absolute BPM)       | `max_heart_rate`       | TrainingPeaks only: falls back to the athlete's TrainingPeaks profile, then 190 BPM, with a coercion warning |
| `power` (absolute watts)          | `ftp`                  | TrainingPeaks only: falls back to the athlete's TrainingPeaks profile, then 200 W, with a coercion warning   |

Fallbacks apply only where the provider needs the baseline. Garmin and TrainingPeaks take heart rate and power percentages directly, so those targets are sent unchanged and the parameter is not used (Garmin still needs `threshold_speed` for `speed_percentage`). The other providers either resolve the percentage against the baseline or carry the baseline alongside the workout so the device can.

### Example: one template, two athletes

#### Create the template (once)

```json
POST /workouts
{
  "name": "Threshold Intervals",
  "sport": "cycling",
  "step_blocks": [{
    "completion_condition": { "type": "reps", "value": 3 },
    "steps": [{
      "completion_condition": { "type": "time", "value": 600 },
      "intensity_type": "active",
      "intensity_targets": [{
        "target_type": "power_percentage",
        "value_low": 95,
        "value_high": 100
      }]
    }]
  }]
}
```

Response: `{ "status": "success", "workout_id": "123" }`

#### Schedule to athlete A (FTP: 200W)

```json
POST /workouts/123/plan?user_id=athlete_a
{
  "planned_date": "2026-02-10",
  "ftp": 200
}
```

**Result on device:** 3x10min @ 190-200W

#### Schedule to athlete B (FTP: 300W)

```json
POST /workouts/123/plan?user_id=athlete_b
{
  "planned_date": "2026-02-10",
  "ftp": 300
}
```

**Result on device:** 3x10min @ 285-300W

These results assume a provider that needs the baseline. Garmin and TrainingPeaks receive 95-100% as a percentage, and the athlete's own FTP on the device or in their TrainingPeaks profile sets the watts.

### Conversion formulas

```
Absolute HR (max %)       = Percentage × max_heart_rate / 100
Absolute HR (threshold %) = Percentage × threshold_heart_rate / 100
Absolute Power            = Percentage × ftp / 100
Absolute Speed            = Percentage × threshold_speed / 100
```

#### Example conversion

Template target: `heart_rate_max_percentage` @ 80-85% Athlete's `max_heart_rate`: 190 BPM

```
Low:  80% × 190 = 152 BPM
High: 85% × 190 = 162 BPM
```

Device shows: 152-162 BPM

### Heart rate zones vs percentages

| Approach                          | When to Use                      |
| --------------------------------- | -------------------------------- |
| `heart_rate_zone` (1-5)           | Device has preconfigured zones   |
| `heart_rate_max_percentage`       | You know user's max HR           |
| `heart_rate_threshold_percentage` | You know user's threshold HR     |
| `heart_rate` (absolute BPM)       | You've pre-calculated the values |

Zone targets are native only on Garmin and Apple. On every other provider Terra expands the zone to a percentage band first, then resolves it against a baseline: threshold HR on COROS and Zepp, max HR on Suunto, Wahoo, TrainingPeaks and Huawei, and FTP for power zones. Send `max_heart_rate`, `threshold_heart_rate` or `ftp` with zone targets too, or the same default baselines apply.

### Pool length

For swimming workouts, `pool_length_meters` can be set in either:

1. **Template** - Default pool length for the workout
2. **Schedule request** - Override for specific user/pool

```json
// Template with default pool length
POST /workouts
{
  "name": "Swim Intervals",
  "sport": "swimming",
  "environment": "pool",
  "pool_length_meters": 25,
  "step_blocks": [...]
}

// Override for 50m pool
POST /workouts/456/plan?user_id=X
{
  "planned_date": "2026-02-10",
  "pool_length_meters": 50
}
```

### Best practices

1. **Always provide required parameters** - Prevents coercion warnings
2. **Store athlete parameters in your app** - Fetch max HR, FTP from user profile
3. **Use percentage targets for personalization** - Same template works for all fitness levels
4. **Use absolute targets for fixed workouts** - When everyone should hit the same number


# Provider compatibility

Which planned workout features and operations each provider supports.

Not all providers support all features. This guide helps you understand what works where.

### Handle unsupported features

When a feature isn't supported, Terra returns a **coercion warning** but still creates the workout:

```json
{
  "status": "success",
  "planned_workout_id": "12345",
  "provider_workout_id": "987654321",
  "warnings": [
    {
      "path": "step_blocks[0].steps[0].intensity_targets",
      "message": "Secondary targets not supported for this sport"
    }
  ]
}
```

`coercion_warnings` carries the same list and is deprecated. Read `warnings`. See [Coercion warnings](/planned-workouts-api/coercion-warnings) for details.

### Operations support

Not all providers support all operations. The table below shows what each provider supports for creating, updating, retrieving, and deleting planned workouts.

| Operation    | Garmin | COROS | Wahoo | Suunto | TrainingPeaks | Huawei | Zepp | Hevy | Apple | Intervals.icu |
| ------------ | ------ | ----- | ----- | ------ | ------------- | ------ | ---- | ---- | ----- | ------------- |
| **Create**   | ✓      | ✓     | ✓     | ✓      | ✓             | ✓      | ✓    | ✓    | ✓     | —             |
| **Update**   | ✓      | ✓\*   | ✓     | ✓      | ✓             | —†     | ✓§   | —    | ✓     | —             |
| **Retrieve** | ✓‡     | —     | ✓     | ✓      | ✓             | —      | —    | —‖   | —     | ✓             |
| **Delete**   | ✓      | ✓     | ✓     | ✓      | ✓             | —      | ✓    | —    | ✓     | —             |

\*COROS does not support in-place updates. Updates are performed by deleting the old workout and creating a new one.

†Huawei does not support updating workout content on the device. When you update a Huawei planned workout, only the planned date changes on Terra's copy. The workout on the device remains unchanged.

‡Garmin only returns workouts that were created by your application's API credentials. Workouts created by other apps or directly on the device will not appear.

§Zepp uses a 7-day sync window. Updates replace all workouts within the current window on the device.

‖Hevy routines are a library, not a calendar. They carry no date, so they are not planned workouts and never appear in the list. A workout pushed to Hevy becomes a routine, and its date is kept only on Terra's copy.

Intervals.icu is read only for planned workouts. Terra lists the athlete's Intervals.icu calendar workouts but cannot create, update or delete them. The athlete connects by entering their Intervals.icu API key on Terra's login screen, the same flow as Hevy.

**When an operation is not supported**, the API still returns a success response. For deletes, the workout is removed from Terra but remains on the user's device.

### Retrieving planned workouts

`GET /v2/plannedWorkouts` returns the workouts you created through Terra and the workouts the athlete created on the provider, where the provider exposes them. Every item has the same shape: `workout` holds the full body (name, sport, step blocks, estimates), `warnings` lists any adjustment made while reading it, and `planned_date` is always set. Provider-created items have `is_external: true` and no `workout_id`, so they cannot be rescheduled or deleted through Terra. A workout you pushed through Terra that the provider echoes back is listed once, as the Terra item.

Provider-created workouts are read from the provider on every call, so the response carries two headers:

| Header                            | Meaning                                                                                                                                                                             |
| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Terra-Provider-Fetch`          | Outcome of the provider read: `ok`, `skipped`, `rate_limited`, `unauthorized`, `unavailable`, `timeout` or `failed`. `skipped` means the provider does not expose planned workouts. |
| `X-Terra-Provider-Data-Truncated` | `true` when provider-created workouts could not be included. The response is still 200 and still contains the workouts you created through Terra.                                   |

`start_date` and `end_date` set the planned-date window and both ends are inclusive. If you omit both, provider-created workouts default to the trailing 30 days, so pass an explicit window to list upcoming workouts. Workouts you created through Terra are not windowed when the dates are omitted.

### Quick reference

<table><thead><tr><th width="128">Feature</th><th align="center">Garmin</th><th align="center">COROS</th><th align="center">Wahoo</th><th align="center">Suunto</th><th align="center">TrainingPeaks</th><th align="center">Huawei</th><th align="center">Zepp</th><th>Hevy</th><th>Apple</th></tr></thead><tbody><tr><td><strong>Sports</strong></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td></td><td></td></tr><tr><td>Running</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Cycling</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Swimming</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Strength</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td>✓</td><td>✓</td></tr><tr><td>Trail Running</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">✓</td><td>—</td><td>—</td></tr><tr><td>Mountain Biking</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td>—</td><td>—</td></tr><tr><td>Backcountry Skiing</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td>—</td><td>—</td></tr><tr><td><strong>Targets</strong></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td></td><td></td></tr><tr><td>Heart Rate (BPM)</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>HR % of Max</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓*</td><td>—</td><td>✓</td></tr><tr><td>HR % of Threshold</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓*</td><td>—</td><td>✓</td></tr><tr><td>HR Zones</td><td align="center">✓</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">✓†</td><td>—</td><td>✓</td></tr><tr><td>Power (Watts)</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">—</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Power % FTP</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓</td><td align="center">—</td><td align="center">✓*</td><td>—</td><td>✓</td></tr><tr><td>Power Zones</td><td align="center">✓</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">✓†</td><td align="center">—</td><td align="center">✓†</td><td>—</td><td>✓</td></tr><tr><td>Pace</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Speed</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓*</td><td align="center">✓</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Cadence</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓¶</td><td>—</td><td>✓</td></tr><tr><td>RPE</td><td align="center">—</td><td align="center">—</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td>—</td><td>—</td></tr><tr><td><strong>Completion</strong></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td></td><td></td></tr><tr><td>Time</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td>✓</td><td>✓</td></tr><tr><td>Distance</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td>✓</td><td>✓</td></tr><tr><td>Reps</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td>✓</td><td>—</td></tr><tr><td>Calories</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">✓</td><td align="center">—</td><td>—</td><td>✓</td></tr><tr><td>HR Trigger</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td>—</td><td>—</td></tr><tr><td>Power Trigger</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td>—</td><td>—</td></tr><tr><td><strong>Structure</strong></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td></td><td></td></tr><tr><td>Multiple targets/step</td><td align="center">✓ (2, cycling/swimming)</td><td align="center">—</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td align="center">✓ (1+cadence)</td><td>—</td><td>—</td></tr><tr><td>Block repeats</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td align="center">✓</td><td>—</td><td>✓</td></tr><tr><td>Exercise names</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td>✓</td><td>—</td></tr><tr><td>Swim strokes</td><td align="center">✓</td><td align="center">✓</td><td align="center">—</td><td align="center">✓</td><td align="center">—</td><td align="center">—</td><td align="center">—</td><td>—</td><td>—</td></tr></tbody></table>

\*Converted by Terra: TrainingPeaks converts absolute values to percentages using athlete profile. Suunto, Huawei, and Zepp convert percentage targets to absolute values using provided athlete parameters or defaults.

†Zone targets converted by Terra: HR zones (1-5) and power zones (1-7) are converted to each provider's native format. HR zones use **threshold HR** as baseline for COROS and Zepp, and **max HR** for Wahoo, TrainingPeaks, Suunto, and Huawei. Power zones use FTP for all providers that support them. Output format varies: percentage (COROS, Wahoo, TrainingPeaks) or absolute BPM/watts (Suunto, Huawei, Zepp).

¶Cadence only supported as a secondary target on Zepp. Must be paired with a primary target (heart rate, power, pace, or speed).

### Provider details

#### Garmin

**Most complete support.** Garmin devices handle nearly all workout features. Supports create, update, retrieve, and delete.

**Strengths:**

* Full strength training with exercise categories
* Swimming with stroke types and equipment
* Up to 2 targets per step (cycling/swimming)
* HR and power trigger completions
* All completion condition types

**Limitations:**

* Time-based steps inside time-based repeat blocks get unwrapped
* Exercise names must match Garmin's catalog (see Exercise Reference)
* Only one equipment item per swimming step: if multiple are provided, the first is used and a coercion warning is returned
* **Retrieve only returns workouts created by your app**: workouts created by other apps or directly on the device will not appear

**Special behaviors:**

* Single values get ±5% range applied
* HR threshold percentage converts to max HR percentage with warning
* Pool length defaults to 25m if not provided

***

#### COROS

**Good support for endurance sports.** Supports create, update (via delete + recreate), and delete. Does not support retrieve.

**Strengths:**

* Running, cycling, swimming, strength
* HR and power percentage targets
* Equipment encoded in step names

**Limitations:**

* Single target per step only (extras ignored)
* Block completion only supports REPS
* No HR/power trigger completions
* Drill stroke type not supported
* **No retrieve support**: the COROS API does not provide an endpoint to fetch existing workouts

**Special behaviors:**

* Single values get ±5% range applied
* Weight converted to grams internally
* Stroke/equipment added to step name in brackets
* Updates delete the old workout and create a new one (the provider\_workout\_id will change)

***

#### Wahoo

**Focused on cycling and running.**

**Strengths:**

* Excellent power zone support
* RPE targets
* Multiple targets per step
* Grade control for smart trainers

**Limitations:**

* No swimming support
* No strength training

**Special behaviors:**

* Percentage targets divided by 100 for API
* Single values expanded ±5%
* Steps without intensity targets get RPE fallback coercion
* Only plan-backed workouts are planned workouts. Sessions the athlete recorded on a Wahoo device have no plan attached and are not returned by the list endpoint
* On the list, a Wahoo gym workout is reported as sport `strength` and a Wahoo cardio workout as `cardio`

***

#### Suunto

**Solid multi-sport support.**

**Strengths:**

* Wide sport type support
* Swimming with stroke metadata
* Strength with exercise text
* Percentage targets converted to absolute values using athlete parameters

**Limitations:**

* Single target per step
* No controls support
* Step names truncated to 13 characters
  * Descriptions truncated to 23 characters

**Special behaviors:**

* Cadence converted from RPM to Hz (÷60)
* Manual lap trigger for open/reps completion
* Percentage targets (HR %, power %, speed %) resolved to absolute values using provided athlete parameters or defaults

***

#### TrainingPeaks

**Training platform integration.**

**Strengths:**

* RPE support
* All sports including triathlon
* Integrates with athlete profile for conversions

**Limitations:**

* Single target per step
* No stroke type support

**Special behaviors:**

* Absolute HR converted to % using athlete's max HR from request, then TrainingPeaks profile, then defaults
* Absolute power converted to % using athlete's FTP from request, then TrainingPeaks profile, then defaults
* Reps estimated as 4 sec/rep (minimum 30 sec)
* Missing profile data falls back to defaults with coercion warning
* `estimated_tss`, `estimated_intensity_factor`, `estimated_distance_meters` and `estimated_calories` are sent to TrainingPeaks on create and on update
* TrainingPeaks ignores TSS, intensity factor and duration when any step target is not RPE: it derives them from the athlete's thresholds instead. Terra returns coercion warnings on `workout.estimated_tss`, `workout.estimated_intensity_factor` and `workout.estimated_duration_seconds` when that happens
* `estimated_tss` must be between 0 and 9999 and `estimated_intensity_factor` between 0 and 5. Outside those ranges the workout is rejected with a 400

***

#### Huawei

**Running workouts only.** Supports create only. Does not support update, retrieve, or delete on the device.

**Strengths:**

* Heart rate targets (absolute BPM, max %, threshold %, zones)
* Pace and speed targets (converted to milliseconds per kilometer)
* Cadence targets (as "steps rate")
* Calorie-based completion conditions
* Block repeats via ActionCombine

**Limitations:**

* Running only: other sports get a coercion warning and appear as a run
* No power targets (running-only device)
* Single target per step (first prioritized target used)
* No strength or swimming support
* **No retrieve support**: the Huawei API does not provide an endpoint to fetch existing workouts
* **No delete support**: the Huawei API does not provide a delete endpoint. Deleting from Terra removes the record from Terra but the workout remains on the user's device
* **No update support**: updates only change the planned date on Terra's copy. The workout on the device is not modified
* **No planned date support**: Huawei does not support scheduling workouts for a specific date. The workout will be available on the device immediately regardless of the `planned_date` value. A coercion warning is always returned noting this.

**Special behaviors:**

* Pace stored as milliseconds per kilometer internally
* HR zones converted to absolute BPM via max HR
* Cooldown and Recovery both map to Huawei's "Relax" action with coercion warning
* Single values expanded ±5%
* Step-level reps converted to separate repeating ActionCombine blocks
* Huawei enforces unique workout names per user: duplicate names return a 400 error
* Huawei may return a 500 "createWorkout error" but still create the workout. When this happens, `provider_workout_id` will be empty and a coercion warning is returned

***

#### Zepp

**Endurance sports with a sync window constraint.** Supports create, update, and delete. Does not support retrieve.

**Strengths:**

* Running, cycling, and swimming support
* Full heart rate and power target coverage including zones and percentages
* Cadence as a secondary target alongside a primary target
* Block repeats
* Pace targets automatically converted from sec/km to m/s

**Limitations:**

* No strength training
* No swim stroke types (ignored with coercion warning)
* No equipment weight targets (ignored with coercion warning)
* No controls support
* **No retrieve support**: the Zepp API does not provide an endpoint to fetch existing workouts
* **7-day sync window**: workouts only appear on the device when scheduled within the next 7 days (today to today + 6 days). Workouts outside this window are kept by Terra but are NOT automatically pushed to the device. They will only be synced when a subsequent write or delete operation for that user triggers a window refresh. To ensure delivery, schedule workouts within the window or trigger a sync by writing/deleting any workout for the user once the date falls within range

**Special behaviors:**

* Full window replacement: every write or delete re-syncs the entire 7-day window to Zepp
* Out-of-window workouts return a coercion warning but are still kept by Terra
* Unsupported sports default to RUNNING with coercion warning
* Missing completion conditions default to 60 seconds
* Cadence only supported as a secondary target: if provided as the only target, a warning is returned
* Step-level reps are wrapped in repeat blocks
* Single values expanded ±5%

***

**Hevy**

Strength training routines only. Supports create. Does not support retrieve, update or delete on the provider.

**Strengths:**

* Full exercise name resolution: Garmin UPPER\_CASE names, Hevy display names, and short aliases all resolve to built-in Hevy template IDs
* Exercise metadata enrichment: custom exercises get correct muscle group, equipment category, and exercise type inferred from the shared exercise metadata registry
* Weight unit conversion (lbs to kg)
* Duration-based and distance-based sets alongside standard weight/reps

**Limitations:**

* Strength only: other sports are accepted but produce a coercion warning; the exercises are still pushed as a routine
* No heart rate, power, pace, speed, or cadence targets (not applicable to strength routines)
* No RPE support: RPE targets are dropped with a coercion warning
* No block repeats: each StepBlock maps to one exercise, each WorkoutStep to one set
* No planned date support: Hevy routines are a library, not a calendar. The routine appears in the user's library immediately regardless of `planned_date`, and the date is kept only on Terra's copy
* No retrieve support: because routines carry no date they are not planned workouts, so they never appear in `GET /v2/plannedWorkouts`
* No delete support: deleting from Terra removes the record from Terra, but the routine remains in the user's Hevy account
* No update support: because routines are not tied to a planned date, updating the planned date has no effect on the provider side

**Special behaviors:**

* If the user's Hevy account hits the custom exercise limit, a 403 is returned per exercise with a coercion warning. The routine is still created with the remaining exercises
* Muscle group for custom exercises is inferred from the exercise name via the Garmin exercise→category mapping (e.g. "Bench Press" → BENCH\_PRESS → chest)

***

**Apple**

Workouts are delivered through the Terra iOS SDK. Terra holds the planned workout until the app next runs, then the SDK schedules it in Apple WorkoutKit and confirms delivery.

**Strengths:**

* Heart rate targets (absolute BPM, % of max, % of threshold, zones)
* Power targets (absolute watts, % of FTP, zones)
* Pace and speed targets
* Cadence targets
* Calorie-based completion conditions
* Block repeats via IntervalBlock iterations

**Limitations:**

* Single target per step: if multiple intensity targets are provided, only the first is used and a coercion warning is returned
* Single warmup and single cooldown per workout: Apple WorkoutKit only supports one of each. Additional warmup or cooldown blocks are dropped with a coercion warning
* No exercise names: WorkoutKit steps are defined by goals and alerts, not exercise names. Strength workouts are limited to timed interval blocks, not structured sets/reps
* No swim stroke types
* No RPE targets
* No multiple targets per step
* No retrieve support: Apple does not expose a server-side API to read scheduled workouts from WorkoutKit

**Special behaviors:**

* `provider_workout_id` is null until the SDK has scheduled the workout on the device. Once it has, the field holds the WorkoutKit identifier
* Unsupported sports (pilates, cardio, trail running, mountain biking, backcountry skiing) are mapped to the closest Apple activity with a coercion warning

***

**Intervals.icu**

Read only. Terra lists the athlete's planned workouts from their Intervals.icu calendar. Terra cannot create, update or delete them.

**Strengths:**

* Structured workouts with power, heart rate, pace and cadence targets, including zone targets
* Repeat groups are preserved
* Planned duration, distance, TSS and intensity factor are returned as workout estimates

**Limitations:**

* No create, update or delete: `POST /workouts/{workout_id}/plan` is not available for Intervals.icu connections
* Repeat groups are only nested when the workout text uses Intervals.icu's documented syntax, which needs a blank line before and after the `3x` line. Written any other way, Intervals.icu parses the group as plain steps and Terra returns them flat
* Pace zone targets are dropped with a coercion warning when the athlete has no threshold pace set
* One level of repeat nesting: a repeat inside a repeat is flattened with a coercion warning

**Connecting:** the athlete enters their Intervals.icu API key on Terra's login screen, the same flow as Hevy. There is no OAuth redirect.

***

### Best practices

1. **Design for Garmin first** - Most complete support
2. **Use percentage targets** - Better cross-provider compatibility
3. **Check coercion warnings** - Know what was modified
4. **Test on target devices** - Verify appearance
5. **Keep step names short** - Some providers truncate


# Coercion warnings

The warnings Terra returns when a provider cannot represent part of a workout, and how to handle them.

### What coercion warnings are

When a workout feature can't be fully represented on a provider's platform, Terra makes adjustments and returns **warnings**. The workout is still created, but some details may differ from what you requested.

Warnings also travel the other way. When `GET /plannedWorkouts` returns a workout the athlete created on the provider's side, Terra converts that workout into the same workout body it uses everywhere else, and anything it could not carry across arrives as a warning on that item.

### Response format

```json
{
  "status": "success",
  "planned_workout_id": "2048",
  "provider_workout_id": "88112233/44556677",
  "warnings": [
    {
      "path": "workout.sport",
      "message": "sport 'rowing' not directly supported by Garmin, using GENERIC"
    },
    {
      "path": "workout.step_blocks[1].steps[0].intensity_targets[1].target_type",
      "message": "Garmin uses heart rate percentage of max HR, not threshold HR. The percentage values will be interpreted as % of max HR."
    }
  ]
}
```

Read `warnings`. It is always present and is an empty array when nothing was adjusted. `coercion_warnings` carries the same list, is deprecated, and on `GET /plannedWorkouts` is a JSON string rather than an array.

### Warnings on listed workouts

`GET /plannedWorkouts` returns workouts created through Terra and workouts the athlete created on the provider's side (`is_external: true`). Both kinds carry the same `workout` body and the same `warnings` array.

On a Terra-created workout, `warnings` says what was lost pushing your template to the provider. On a provider-created workout, it says what was lost reading the provider's workout back into a Terra workout body. For example, Intervals.icu nests a repeat group only when the workout text uses its documented syntax, a blank line before and after the `3x` line. Written any other way, the steps come back flat.

Two warning paths tell you where a missing body came from:

| Warning path                           | What it means                                                                                                                      |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `workout` (with `workout: null`)       | Terra could not load the stored body of a workout you created.                                                                     |
| `step_blocks` (with `step_blocks: []`) | The provider returned the workout, but its step file could not be fetched. Name, sport and estimates are there, the steps are not. |

Provider-created workouts are listed for Garmin, Wahoo, Suunto, TrainingPeaks and Intervals.icu. Intervals.icu is read only: you can list its workouts but not push to it, so its warnings always come from reading.

### Common warning scenarios

#### Missing athlete parameters

**Cause:** Workout uses percentage targets but required parameter wasn't provided.

```json
{
  "path": "workout.step_blocks[0].steps[0].intensity_targets[0]",
  "message": "HR threshold percentage target requires a threshold HR baseline. Using default threshold HR of 170 bpm. Provide threshold_heart_rate for accurate targets."
}
```

**Fix:** Include the required parameter in your schedule request:

```json
POST /workouts/123/plan?user_id=X
{
  "planned_date": "2026-02-10",
  "threshold_heart_rate": 165
}
```

#### Unsupported sport type

**Cause:** Provider doesn't support the workout's sport.

```json
{
  "path": "workout.sport",
  "message": "sport 'rowing' not directly supported by Garmin, using GENERIC"
}
```

**Impact:** Workout created but may display incorrectly on device.

#### Too many targets

**Cause:** Step has more targets than provider supports.

```json
{
  "path": "workout.step_blocks[0].steps[0].intensity_targets",
  "message": "Zepp supports one primary target and one optional cadence secondary target, ignoring 2 extra target(s)"
}
```

**Fix:** Prioritize your most important target as the first one.

#### Unsupported target type

**Cause:** Provider doesn't support the target type.

```json
{
  "path": "workout.step_blocks[0].steps[0].intensity_targets[0].target_type",
  "message": "Target type 'cadence' not supported by Garmin for this sport. Using OPEN instead."
}
```

#### Swimming pool length missing

**Cause:** Swimming workout without pool length.

```json
{
  "path": "workout.pool_length_meters",
  "message": "Pool length not provided for swimming workout. Defaulting to 25 meters."
}
```

**Fix:** Set `pool_length_meters` in template or schedule request.

#### Unrecognized exercise name

**Cause:** Strength exercise name doesn't match Garmin's catalog.

```json
{
  "path": "workout.step_blocks[0].steps[0].strength.exercise_name",
  "message": "Could not determine category for exercise name 'CUSTOM_EXERCISE', dropping exercise name/category but keeping weight data"
}
```

**Impact:** Step still created, weight preserved, but exercise name/category not shown.

**Fix:** Use a recognized exercise name.

#### Block completion coercion

**Cause:** Provider doesn't support the block completion type.

```json
{
  "path": "workout.step_blocks[1].completion_condition",
  "message": "Time-based block completion not supported. Block will execute once."
}
```

#### Intensity type coercion

**Cause:** Provider doesn't support the intensity type.

```json
{
  "path": "workout.step_blocks[0].steps[0].intensity_type",
  "message": "RECOVERY intensity coerced to ACTIVE."
}
```

#### Estimates ignored (TrainingPeaks)

**Cause:** The workout supplies `estimated_tss`, `estimated_intensity_factor` or `estimated_duration_seconds`, and at least one step target is not RPE.

```json
{
  "path": "workout.estimated_tss",
  "message": "TrainingPeaks derives this from the step targets when any target is not RPE; the supplied value is ignored"
}
```

**Impact:** Terra forwards `estimated_tss`, `estimated_intensity_factor`, `estimated_distance_meters` and `estimated_calories` to TrainingPeaks when you plan a workout and when you reschedule it. TrainingPeaks recalculates TSS, intensity factor and duration from the athlete's own thresholds whenever a step uses anything other than an RPE target. You get one warning per value you supplied. Distance and calories are unaffected.

**Fix:** Use RPE targets throughout if your own TSS and intensity factor need to stick. Otherwise treat TrainingPeaks' numbers as the source of truth.

`estimated_tss` must be between 0 and 9999 and `estimated_intensity_factor` between 0 and 5. Outside those ranges the template is rejected with a 400 when you create it, not coerced.

#### Sync window (Zepp)

**Cause:** Workout scheduled outside the provider's sync window.

```json
{
  "path": "planned_date",
  "message": "workout date is outside Zepp's 7-day sync window; it will not appear on the device until it falls within range"
}
```

**Impact:** The planned workout is saved and returned by the API, but it won't appear on the device until it enters the 7-day window (today to today + 6 days). It is pushed the next time you create, reschedule or delete a workout for that user, which refreshes the window. Nothing is pushed in the background.

#### Unsupported sport (Zepp)

**Cause:** Sport type not natively supported by Zepp.

```json
{
  "path": "workout.sport",
  "message": "sport 'strength' not supported by Zepp, defaulting to 'RUNNING'. Supported sports: RUNNING, CYCLING, LAP_SWIMMING"
}
```

**Impact:** Workout is created but displays as a running workout on the device.

#### Cadence as primary target (Zepp)

**Cause:** Cadence provided as the only target without a primary target.

```json
{
  "path": "workout.step_blocks[0].steps[0].intensity_targets[0].target_type",
  "message": "cadence is only supported as a secondary target on Zepp; provide a primary target (pace, power, heart_rate) alongside it"
}
```

**Fix:** Add a primary target (heart rate, power, pace, or speed) and use cadence as a secondary target.

#### Swim stroke ignored (Zepp)

**Cause:** Zepp does not support stroke type metadata.

```json
{
  "path": "workout.step_blocks[0].steps[0].swimming.stroke_type",
  "message": "Zepp does not support stroke types, 'butterfly' will be ignored"
}
```

**Impact:** Swimming workout is created but stroke type is not displayed on the device.

#### Impossible pace or speed (Suunto)

**Cause:** Usually because of a pace sent in minutes per kilometre, instead of seconds per km.

**Impact:** The workout is created without that step's target.

**Fix:** Send pace in seconds per kilometre: 4:30/km is `270`.

### Handle warnings in your app

#### Log for debugging

```python
response = create_planned_workout(workout_id, user_id, date, params)

for warning in response.get('warnings', []):
    logger.warning("Workout coercion: %s - %s", warning['path'], warning['message'])
```

#### Show to users (optional)

For user-facing apps, you might surface relevant warnings:

```javascript
if (response.warnings?.length > 0) {
  showNotification({
    type: 'info',
    message: 'Some workout features were adjusted for your device.',
    details: response.warnings.map(w => w.message)
  });
}
```

#### Ignore if acceptable

Many warnings are informational. If the workout still works for your use case, you can safely ignore them.

### Prevent warnings

1. **Check Provider Compatibility** before building workouts
2. **Always provide athlete parameters** for percentage-based targets
3. **Use single targets** for maximum compatibility
4. **Use recognized exercise names** for strength training
5. **Set pool length** for swimming workouts
6. **Stick to common intensity types**: warmup, active, rest, cooldown


# Exercise reference

How strength exercise names are matched to each provider's exercise catalog.

### Overview

For strength training workouts on Garmin, exercise names are matched against Garmin's catalog of 1,600+ exercises. This enables proper categorization and display on the device.

Garmin only accepts exercise names when the workout's `sport` is `strength`, `cardio`, `yoga` or `pilates`. On any other sport the exercise name and weight are dropped, and no coercion warning is returned.

For all other devices where custom names are supported, exercise names:

1. Are title cased
2. Get underscores "\_" converted to spaces " "

### Name flexibility

Garmin exercise name lookup is **flexible**. All of these work:

| Input                   | Normalized              | Garmin      | Hevy                              |
| ----------------------- | ----------------------- | ----------- | --------------------------------- |
| "BARBELL\_BENCH\_PRESS" | BARBELL\_BENCH\_PRESS   | ✓ Found     | ✓ Bench Press (Barbell)           |
| "barbell\_bench\_press" | BARBELL\_BENCH\_PRESS   | ✓ Found     | ✓ Bench Press (Barbell)           |
| "Barbell Bench Press"   | BARBELL\_BENCH\_PRESS   | ✓ Found     | ✓ Bench Press (Barbell)           |
| "barbell bench press"   | BARBELL\_BENCH\_PRESS   | ✓ Found     | ✓ Bench Press (Barbell)           |
| "Bench Press (Barbell)" | BENCH\_PRESS\_(BARBELL) | ✗ Not found | ✓ Bench Press (Barbell)           |
| "Bench Press"           | BENCH\_PRESS            | ✗ Not found | ✓ Bench Press (Barbell) via alias |
| "My Custom Exercise"    | MY\_CUSTOM\_EXERCISE    | ✗ Not found | ✗ → Custom exercise created       |

**Normalization process:**

1. Replace spaces with underscores
2. Convert to UPPERCASE
3. Look up in exercise catalog

Hevy resolves the name in this order:

1. Normalized name in the exercise catalog, where it carries a Hevy template
2. Exact Hevy display name (e.g. Squat (Barbell)) or short alias (e.g. Bench Press → Bench Press (Barbell))
3. No match: a custom exercise is created

Step 2 is an exact match, so case and punctuation must match Hevy's display name.

### What happens if a name is not found

Garmin:

* ⚠️ Coercion warning returned
* Exercise name and category omitted from Garmin workout
* Weight data preserved
* Step still created

Hevy:

* Custom exercise template created automatically on the user's Hevy account
* Muscle group and equipment inferred from the name where possible
* ⚠️ Coercion warning returned if the custom exercise cannot be created, for example when the account's custom exercise limit is reached
* In that case the exercise is left out of the routine. Unlike Garmin, the step is not created

Suunto, TrainingPeaks, COROS and Zepp show the name as Title Case With Spaces Instead Of Underscores, regardless of input format. Wahoo and Huawei have no per-exercise name field, so the name is dropped. Intervals.icu is read only for planned workouts, so nothing is pushed to it.

### What comes back on the list

`GET /v2/plannedWorkouts` returns both the workouts you created through Terra and the ones the athlete created on the provider, each with the full `workout` body.

* Workouts you created through Terra return `strength.exercise_name` exactly as you sent it
* Workouts created on Garmin return `strength.exercise_name` in Title Case, for example `Barbell Bench Press`, not the `BARBELL_BENCH_PRESS` form used below. Normalize it the same way (spaces to underscores, UPPERCASE) to match it against the catalog

### Common exercises by category

#### BENCH\_PRESS

```
BARBELL_BENCH_PRESS
DUMBBELL_BENCH_PRESS
INCLINE_BARBELL_BENCH_PRESS
INCLINE_DUMBBELL_BENCH_PRESS
DECLINE_DUMBBELL_BENCH_PRESS
CLOSE_GRIP_BARBELL_BENCH_PRESS
```

#### SQUAT

```
BARBELL_BACK_SQUAT
BARBELL_FRONT_SQUAT
GOBLET_SQUAT
DUMBBELL_SQUAT
SUMO_SQUAT
AIR_SQUAT
```

#### DEADLIFT

```
BARBELL_DEADLIFT
ROMANIAN_DEADLIFT
SUMO_DEADLIFT
SINGLE_LEG_BARBELL_DEADLIFT
DUMBBELL_DEADLIFT
```

#### ROW

```
BENT_OVER_ROW_WITH_BARBELL
BARBELL_ROW
DUMBBELL_ROW
ONE_ARM_BENT_OVER_ROW
CABLE_ROW_STANDING
SEATED_CABLE_ROW
```

#### SHOULDER\_PRESS

```
OVERHEAD_BARBELL_PRESS
BARBELL_SHOULDER_PRESS
DUMBBELL_SHOULDER_PRESS
ARNOLD_PRESS
MILITARY_PRESS
BARBELL_PUSH_PRESS
```

#### CURL

```
BARBELL_BICEPS_CURL
DUMBBELL_BICEPS_CURL
DUMBBELL_HAMMER_CURL
EZ_BAR_PREACHER_CURL
ONE_ARM_CONCENTRATION_CURL
CABLE_BICEPS_CURL
```

#### TRICEPS\_EXTENSION

```
TRICEPS_PRESSDOWN
ROPE_PRESSDOWN
LYING_EZ_BAR_TRICEPS_EXTENSION
OVERHEAD_DUMBBELL_TRICEPS_EXTENSION
CABLE_LYING_TRICEPS_EXTENSION
```

#### PLANK

```
STRAIGHT_ARM_PLANK
SIDE_PLANK
PLANK_WITH_ARM_RAISE
PLANK_WITH_LEG_LIFT
WEIGHTED_PLANK
```

#### LUNGE

```
WALKING_LUNGE
BARBELL_LUNGE
DUMBBELL_LUNGE
BARBELL_REVERSE_LUNGE
DUMBBELL_REVERSE_LUNGE
SIDE_LUNGE
```

#### PULL\_UP

```
PULL_UP
CHIN_UP
WIDE_GRIP_PULL_UP
CLOSE_GRIP_CHIN_UP
BAND_ASSISTED_PULL_UP
WEIGHTED_PULL_UP
```

### Full reference

For the complete list of 1,600+ exercises organized by category, see the full reference in the next section

### Usage example

```json
{
  "name": "Push Day",
  "sport": "strength",
  "step_blocks": [
    {
      "completion_condition": { "type": "reps", "value": 4 },
      "steps": [{
        "completion_condition": { "type": "reps", "value": 8 },
        "intensity_type": "active",
        "strength": {
          "exercise_name": "barbell bench press",
          "weight": 80,
          "weight_display_unit": "kg"
        }
      }]
    },
    {
      "completion_condition": { "type": "reps", "value": 3 },
      "steps": [{
        "completion_condition": { "type": "reps", "value": 10 },
        "intensity_type": "active",
        "strength": {
          "exercise_name": "DUMBBELL_SHOULDER_PRESS",
          "weight": 25,
          "weight_display_unit": "kg"
        }
      }]
    }
  ]
}
```

### Tips

1. **Search the full reference** - Use Ctrl+F to find exercises
2. **Try common variations** - If one name fails, try another
3. **Check coercion warnings** - They tell you if lookup failed
4. **Use descriptive fallbacks** - Suunto, TrainingPeaks, COROS and Zepp show your text in Title Case


# Garmin and Hevy exercise reference

Every Garmin exercise name Terra accepts, grouped by category, and how they map to Hevy.

## Garmin exercise names

This reference lists all supported Garmin exercise names, grouped by category.

If you're already using Garmin exercise names, they work for Hevy too. Terra applies the same normalization (spaces to underscores, UPPERCASE), then matches the result to a Hevy exercise. 238 of the names below map directly to a Hevy built-in exercise. For every other name Terra creates a custom exercise on the athlete's Hevy account, titled with the name you sent, with muscle group and equipment inferred from it.

### Exercise name lookup rules

Terra's exercise name lookup is **flexible**:

| Input                   | Normalized To         | Result  |
| ----------------------- | --------------------- | ------- |
| `"BARBELL_BENCH_PRESS"` | `BARBELL_BENCH_PRESS` | ✓ Found |
| `"barbell_bench_press"` | `BARBELL_BENCH_PRESS` | ✓ Found |
| `"Barbell Bench Press"` | `BARBELL_BENCH_PRESS` | ✓ Found |
| `"barbell bench press"` | `BARBELL_BENCH_PRESS` | ✓ Found |
| `"BARBELL BENCH PRESS"` | `BARBELL_BENCH_PRESS` | ✓ Found |

**Normalization process:**

1. Replace all spaces with underscores
2. Convert to UPPERCASE
3. Look up in the exercise map

Garmin only accepts exercise names on `strength`, `cardio`, `yoga` and `pilates` workouts. On any other sport the `strength` block, including the exercise name and the weight, is ignored and no coercion warning is returned.

**If the exercise is not found on Garmin:**

* Exercise name and category are dropped from the Garmin workout
* Weight data is preserved and the step is still created
* A coercion warning is returned

**If the exercise is not found on Hevy:**

* Terra creates a custom exercise on the athlete's Hevy account, inferring muscle group and equipment from the name
* A coercion warning is returned only if Hevy refuses to create it, for example when the athlete's custom exercise limit is reached. That exercise is then left out of the routine

Suunto, TrainingPeaks, COROS and Zepp show the name in Title Case with spaces. Wahoo and Huawei have no per-exercise name field.

**Reading workouts back:**

Workouts created on Garmin come back from `GET /v2/plannedWorkouts` with `strength.exercise_name` in Title Case, for example `Barbell Bench Press`, not the `BARBELL_BENCH_PRESS` form used here. Normalize it the same way (spaces to underscores, UPPERCASE) to match it against the list below. Workouts you created through Terra come back with the name exactly as you sent it.

***

### Categories (49 total)

* BANDED\_EXERCISES (44)
* BATTLE\_ROPE (28)
* BENCH\_PRESS (27)
* BIKE\_OUTDOOR (1)
* CALF\_RAISE (21)
* CARDIO (21)
* CARRY (9)
* CHOP (23)
* CORE (87)
* CRUNCH (84)
* CURL (47)
* DEADLIFT (23)
* ELLIPTICAL (1)
* FLOOR\_CLIMB (1)
* FLYE (11)
* HIP\_RAISE (48)
* HIP\_STABILITY (35)
* HIP\_SWING (4)
* HYPEREXTENSION (39)
* INDOOR\_BIKE (3)
* LADDER (2)
* LATERAL\_RAISE (36)
* LEG\_CURL (14)
* LEG\_RAISE (22)
* LUNGE (90)
* MOVE (64)
* OLYMPIC\_LIFT (28)
* PLANK (134)
* PLYO (38)
* POSE (85)
* PULL\_UP (46)
* PUSH\_UP (90)
* ROW (50)
* RUN (5)
* RUN\_INDOOR (2)
* SANDBAG (12)
* SHOULDER\_PRESS (28)
* SHOULDER\_STABILITY (36)
* SHRUG (19)
* SIT\_UP (41)
* SLED (5)
* SLEDGE\_HAMMER (2)
* SQUAT (90)
* STAIR\_STEPPER (9)
* SUSPENSION (18)
* TIRE (1)
* TOTAL\_BODY (18)
* TRICEPS\_EXTENSION (43)
* WARM\_UP (39)

***

### BANDED\_EXERCISES

**44 exercises**

```
AB_TWIST
BACK_EXTENSION
BICYCLE_CRUNCH
CALF_RAISES
CLAM_SHELLS
CURL
DEADBUG
DEADLIFT
DONKEY_KICK
EXTERNAL_ROTATION
EXTERNAL_ROTATION_AT_90_DEGREE_ABDUCTION
FIRE_HYDRANT
FLY
FRONT_RAISE
GLUTE_BRIDGE
HAMSTRING_CURLS
HIGH_PLANK_LEG_LIFTS
HIP_EXTENSION
INTERNAL_ROTATION
JUMPING_JACK
KNEELING_CRUNCH
LATERAL_BAND_WALKS
LATERAL_RAISE
LATPULL
LEG_ABDUCTION
LEG_ADDUCTION
LEG_EXTENSION
LUNGE
PLANK
PULL_APART
PUSH_UPS
REVERSE_CRUNCH
ROW
SHOULDER_ABDUCTION
SHOULDER_EXTENSION
SHOULDER_EXTERNAL_ROTATION
SHOULDER_FLEXION_TO_90_DEGREES
SIDE_PLANK_LEG_LIFTS
SQUAT
SQUAT_TO_PRESS
TRICEP_EXTENSION
TRICEP_KICKBACK
UPRIGHT_ROW
WALL_CRAWL_WITH_EXTERNAL_ROTATION
```

### BATTLE\_ROPE

**28 exercises**

```
ALTERNATING_FIGURE_EIGHT
ALTERNATING_JUMP_WAVE
ALTERNATING_KNEELING_TO_STANDING_WAVE
ALTERNATING_LUNGE_WAVE
ALTERNATING_SQUAT_WAVE
ALTERNATING_WAVE
ALTERNATING_WAVE_WITH_LATERAL_SHUFFLE
CLAP_WAVE
DOUBLE_ARM_FIGURE_EIGHT
DOUBLE_ARM_SIDE_TO_SIDE_SNAKE
DOUBLE_ARM_SIDE_WAVE
DOUBLE_ARM_SLAM
DOUBLE_ARM_WAVE
GRAPPLER_TOSS
HIP_TOSS
INSIDE_CIRCLE
IN_AND_OUT_WAVE
JUMPING_JACKS
OUTSIDE_CIRCLE
RAINBOW
SIDEWINDER
SIDE_PLANK_WAVE
SITTING_RUSSIAN_TWIST
SNAKE_WAVE
SPLIT_JACK
STAGE_COACH
ULTIMATE_WARRIOR
UPPER_CUTS
```

### BENCH\_PRESS

**27 exercises**

```
ALTERNATING_DUMBBELL_CHEST_PRESS
ALTERNATING_DUMBBELL_CHEST_PRESS_ON_SWISS_BALL
BARBELL_BENCH_PRESS
BARBELL_BOARD_BENCH_PRESS
BARBELL_FLOOR_PRESS
CLOSE_GRIP_BARBELL_BENCH_PRESS
DECLINE_DUMBBELL_BENCH_PRESS
DUMBBELL_BENCH_PRESS
DUMBBELL_FLOOR_PRESS
INCLINE_BARBELL_BENCH_PRESS
INCLINE_DUMBBELL_BENCH_PRESS
INCLINE_SMITH_MACHINE_BENCH_PRESS
ISOMETRIC_BARBELL_BENCH_PRESS
KETTLEBELL_CHEST_PRESS
NEUTRAL_GRIP_DUMBBELL_BENCH_PRESS
NEUTRAL_GRIP_DUMBBELL_INCLINE_BENCH_PRESS
ONE_ARM_FLOOR_PRESS
PARTIAL_LOCKOUT
REVERSE_GRIP_BARBELL_BENCH_PRESS
REVERSE_GRIP_INCLINE_BENCH_PRESS
SINGLE_ARM_CABLE_CHEST_PRESS
SINGLE_ARM_DUMBBELL_BENCH_PRESS
SMITH_MACHINE_BENCH_PRESS
SWISS_BALL_DUMBBELL_CHEST_PRESS
TRIPLE_STOP_BARBELL_BENCH_PRESS
WEIGHTED_ONE_ARM_FLOOR_PRESS
WIDE_GRIP_BARBELL_BENCH_PRESS
```

### BIKE\_OUTDOOR

**1 exercises**

```
BIKE
```

### CALF\_RAISE

**21 exercises**

```
DONKEY_CALF_RAISE
SEATED_CALF_RAISE
SEATED_DUMBBELL_TOE_RAISE
SINGLE_LEG_BENT_KNEE_CALF_RAISE
SINGLE_LEG_DECLINE_PUSH_UP
SINGLE_LEG_DONKEY_CALF_RAISE
SINGLE_LEG_HIP_RAISE_WITH_KNEE_HOLD
SINGLE_LEG_STANDING_CALF_RAISE
SINGLE_LEG_STANDING_DUMBBELL_CALF_RAISE
STANDING_BARBELL_CALF_RAISE
STANDING_CALF_RAISE
STANDING_DUMBBELL_CALF_RAISE
WEIGHTED_DONKEY_CALF_RAISE
WEIGHTED_SEATED_CALF_RAISE
WEIGHTED_SINGLE_LEG_BENT_KNEE_CALF_RAISE
WEIGHTED_SINGLE_LEG_DONKEY_CALF_RAISE
WEIGHTED_STANDING_CALF_RAISE
_3_WAY_CALF_RAISE
_3_WAY_SINGLE_LEG_CALF_RAISE
_3_WAY_WEIGHTED_CALF_RAISE
_3_WAY_WEIGHTED_SINGLE_LEG_CALF_RAISE
```

### CARDIO

**21 exercises**

```
BOB_AND_WEAVE_CIRCLE
CARDIO_CORE_CRAWL
DOUBLE_UNDER
JUMP_ROPE
JUMP_ROPE_CROSSOVER
JUMP_ROPE_JOG
SKI_MOGULS
SPLIT_JACKS
SQUAT_JACKS
TRIPLE_UNDER
WEIGHTED_BOB_AND_WEAVE_CIRCLE
WEIGHTED_CARDIO_CORE_CRAWL
WEIGHTED_DOUBLE_UNDER
WEIGHTED_JUMPING_JACKS
WEIGHTED_JUMP_ROPE
WEIGHTED_JUMP_ROPE_CROSSOVER
WEIGHTED_JUMP_ROPE_JOG
WEIGHTED_SKI_MOGULS
WEIGHTED_SPLIT_JACKS
WEIGHTED_SQUAT_JACKS
WEIGHTED_TRIPLE_UNDER
```

### CARRY

**9 exercises**

```
BAR_HOLDS
DUMBBELL_WAITER_CARRY
FARMERS_CARRY
FARMERS_CARRY_ON_TOES
FARMERS_CARRY_WALK_LUNGE
FARMERS_WALK
FARMERS_WALK_ON_TOES
HEX_DUMBBELL_HOLD
OVERHEAD_CARRY
```

### CHOP

**23 exercises**

```
CABLE_PULL_THROUGH
CABLE_ROTATIONAL_LIFT
CABLE_WOODCHOP
CROSS_CHOP_TO_KNEE
DUMBBELL_CHOP
HALF_KNEELING_ROTATION
HALF_KNEELING_ROTATIONAL_CHOP
HALF_KNEELING_ROTATIONAL_REVERSE_CHOP
HALF_KNEELING_STABILITY_CHOP
HALF_KNEELING_STABILITY_REVERSE_CHOP
KNEELING_ROTATIONAL_CHOP
KNEELING_ROTATIONAL_REVERSE_CHOP
KNEELING_STABILITY_CHOP
KNEELING_WOODCHOPPER
MEDICINE_BALL_WOOD_CHOPS
POWER_SQUAT_CHOPS
STANDING_ROTATIONAL_CHOP
STANDING_SPLIT_ROTATIONAL_CHOP
STANDING_SPLIT_ROTATIONAL_REVERSE_CHOP
STANDING_STABILITY_REVERSE_CHOP
WEIGHTED_CROSS_CHOP_TO_KNEE
WEIGHTED_HALF_KNEELING_ROTATION
WEIGHTED_POWER_SQUAT_CHOPS
```

### CORE

**87 exercises**

```
ABS_JABS
ALTERNATING_PLATE_REACH
ALTERNATING_SLIDE_OUT
ARM_AND_LEG_EXTENSION_ON_KNEES
BARBELL_ROLLOUT
BICEP_CURL_WITH_LEG_EXTENSION
BICEP_CURL_WITH_LEG_EXTENSION_WITH_WEIGHTS
BICYCLE
BODY_BAR_OBLIQUE_TWIST
CABLE_CORE_PRESS
CABLE_SIDE_BEND
CAT_COW
CORKSCREW
CRESCENT_CIRCLE
CRISS_CROSS
CYCLING_RUSSIAN_TWIST
DOUBLE_LEG_STRETCH
ELEVATED_FEET_RUSSIAN_TWIST
GHD_BACK_EXTENSIONS
HALF_TURKISH_GET_UP
HANGING_L_SIT
INCHWORM
KETTLEBELL_WINDMILL
KNEELING_AB_WHEEL
KNEE_FOLDS
LOWER_LIFT
LOWER_LIFT_WITH_WEIGHTS
L_SIT
MODIFIED_FRONT_LEVER
NECK_PULL
OPEN_KNEE_TUCKS
OVERHEAD_WALK
PELVIC_CLOCKS
RING_L_SIT
ROLLING
ROLL_OVER
ROLL_UP
ROWING_1
ROWING_1_WITH_WEIGHTS
ROWING_2
ROWING_2_WITH_WEIGHTS
RUSSIAN_TWIST
SCISSORS
SCISSORS_WITH_WEIGHTS
SIDE_ABS_LEG_LIFT
SIDE_BEND
SINGLE_LEG_CIRCLES
SINGLE_LEG_STRETCH
SINGLE_LEG_STRETCH_WITH_WEIGHTS
SWAN
SWIMMING
SWISS_BALL_JACKKNIFE
SWISS_BALL_PIKE
SWISS_BALL_ROLLOUT
TEASER
THE_HUNDRED
TOES_TO_ELBOWS
TRIANGLE_HIP_PRESS
TRX_SUSPENDED_JACKKNIFE
TURKISH_GET_UP
U_BOAT
WEIGHTED_ABS_JABS
WEIGHTED_ALTERNATING_SLIDE_OUT
WEIGHTED_BARBELL_ROLLOUT
WEIGHTED_CRESCENT_CIRCLE
WEIGHTED_CRISS_CROSS
WEIGHTED_CYCLING_RUSSIAN_TWIST
WEIGHTED_DOUBLE_LEG_STRETCH
WEIGHTED_ELEVATED_FEET_RUSSIAN_TWIST
WEIGHTED_GHD_BACK_EXTENSIONS
WEIGHTED_HANGING_L_SIT
WEIGHTED_KNEELING_AB_WHEEL
WEIGHTED_L_SIT
WEIGHTED_MODIFIED_FRONT_LEVER
WEIGHTED_OPEN_KNEE_TUCKS
WEIGHTED_RING_L_SIT
WEIGHTED_SIDE_ABS_LEG_LIFT
WEIGHTED_SIDE_BEND
WEIGHTED_SWISS_BALL_JACKKNIFE
WEIGHTED_SWISS_BALL_PIKE
WEIGHTED_SWISS_BALL_ROLLOUT
WEIGHTED_THE_HUNDRED
WEIGHTED_TRIANGLE_HIP_PRESS
WEIGHTED_TRX_SUSPENDED_JACKKNIFE
WEIGHTED_U_BOAT
WEIGHTED_WINDMILL_SWITCHES
WINDMILL_SWITCHES
```

### CRUNCH

**84 exercises**

```
CABLE_CRUNCH
CIRCULAR_ARM_CRUNCH
CROSSED_ARMS_CRUNCH
CROSS_LEG_REVERSE_CRUNCH
CRUNCH
CRUNCH_CHOP
DOUBLE_CRUNCH
ELBOW_TO_KNEE_CRUNCH
FLUTTER_KICKS
FOAM_ROLLER_REVERSE_CRUNCH_ON_BENCH
FOAM_ROLLER_REVERSE_CRUNCH_WITH_DUMBBELL
FOAM_ROLLER_REVERSE_CRUNCH_WITH_MEDICINE_BALL
FROG_PRESS
HANGING_KNEE_RAISE_OBLIQUE_CRUNCH
HIP_CROSSOVER
HOLLOW_ROCK
INCLINE_REVERSE_CRUNCH
KNEELING_CABLE_CRUNCH
KNEELING_CROSS_CRUNCH
KNEELING_OBLIQUE_CABLE_CRUNCH
KNEES_TO_ELBOW
LEG_CLIMB_CRUNCH
LEG_EXTENSIONS
LEG_LEVERS
MCGILL_CURL_UP
MODIFIED_PILATES_ROLL_UP_WITH_BALL
PILATES_CRUNCH
PILATES_ROLL_UP_WITH_BALL
RAISED_LEGS_CRUNCH
REVERSE_CRUNCH_ON_A_BENCH
REVERSE_CURL_AND_LIFT
ROTATIONAL_LIFT
SEATED_ALTERNATING_REVERSE_CRUNCH
SEATED_LEG_U
SIDE_TO_SIDE_CRUNCH_AND_WEAVE
SINGLE_LEG_REVERSE_CRUNCH
SKATER_CRUNCH_CROSS
STANDING_CABLE_CRUNCH
STANDING_SIDE_CRUNCH
STEP_CLIMB
STRAIGHT_LEG_CRUNCH_WITH_BALL
SWISS_BALL_CRUNCH
SWISS_BALL_REVERSE_CRUNCH
SWISS_BALL_RUSSIAN_TWIST
SWISS_BALL_SIDE_CRUNCH
THORACIC_CRUNCHES_ON_FOAM_ROLLER
TOES_TO_BAR
TRICEPS_CRUNCH
WEIGHTED_BICYCLE_CRUNCH
WEIGHTED_CROSSED_ARMS_CRUNCH
WEIGHTED_CROSS_LEG_REVERSE_CRUNCH
WEIGHTED_CRUNCH
WEIGHTED_CRUNCH_CHOP
WEIGHTED_DOUBLE_CRUNCH
WEIGHTED_ELBOW_TO_KNEE_CRUNCH
WEIGHTED_FLUTTER_KICKS
WEIGHTED_FOAM_ROLLER_REVERSE_CRUNCH_ON_BENCH
WEIGHTED_HANGING_KNEE_RAISE_OBLIQUE_CRUNCH
WEIGHTED_HIP_CROSSOVER
WEIGHTED_HOLLOW_ROCK
WEIGHTED_INCLINE_REVERSE_CRUNCH
WEIGHTED_KNEELING_CROSS_CRUNCH
WEIGHTED_LEG_EXTENSIONS
WEIGHTED_MCGILL_CURL_UP
WEIGHTED_MODIFIED_PILATES_ROLL_UP_WITH_BALL
WEIGHTED_PILATES_CRUNCH
WEIGHTED_PILATES_ROLL_UP_WITH_BALL
WEIGHTED_RAISED_LEGS_CRUNCH
WEIGHTED_REVERSE_CRUNCH
WEIGHTED_REVERSE_CRUNCH_ON_A_BENCH
WEIGHTED_REVERSE_CURL_AND_LIFT
WEIGHTED_ROTATIONAL_LIFT
WEIGHTED_SEATED_ALTERNATING_REVERSE_CRUNCH
WEIGHTED_SEATED_LEG_U
WEIGHTED_SIDE_TO_SIDE_CRUNCH_AND_WEAVE
WEIGHTED_SINGLE_LEG_REVERSE_CRUNCH
WEIGHTED_SKATER_CRUNCH_CROSS
WEIGHTED_STEP_CLIMB
WEIGHTED_SWISS_BALL_CRUNCH
WEIGHTED_SWISS_BALL_REVERSE_CRUNCH
WEIGHTED_SWISS_BALL_RUSSIAN_TWIST
WEIGHTED_SWISS_BALL_SIDE_CRUNCH
WEIGHTED_THORACIC_CRUNCHES_ON_FOAM_ROLLER
WEIGHTED_TOES_TO_BAR
```

### CURL

**47 exercises**

```
ALTERNATING_DUMBBELL_BICEPS_CURL
ALTERNATING_DUMBBELL_BICEPS_CURL_ON_SWISS_BALL
ALTERNATING_INCLINE_DUMBBELL_BICEPS_CURL
BARBELL_BICEPS_CURL
BARBELL_REVERSE_WRIST_CURL
BARBELL_WRIST_CURL
BEHIND_THE_BACK_BARBELL_REVERSE_WRIST_CURL
BEHIND_THE_BACK_ONE_ARM_CABLE_CURL
CABLE_BICEPS_CURL
CABLE_HAMMER_CURL
CHEATING_BARBELL_BICEPS_CURL
CLOSE_GRIP_EZ_BAR_BICEPS_CURL
CROSS_BODY_DUMBBELL_HAMMER_CURL
DEAD_HANG_BICEPS_CURL
DECLINE_HAMMER_CURL
DUMBBELL_BICEPS_CURL
DUMBBELL_BICEPS_CURL_WITH_STATIC_HOLD
DUMBBELL_HAMMER_CURL
DUMBBELL_REVERSE_WRIST_CURL
DUMBBELL_WRIST_CURL
EZ_BAR_PREACHER_CURL
FORWARD_BEND_BICEPS_CURL
HAMMER_CURL_TO_PRESS
INCLINE_DUMBBELL_BICEPS_CURL
INCLINE_OFFSET_THUMB_DUMBBELL_CURL
KETTLEBELL_BICEPS_CURL
LYING_CONCENTRATION_CABLE_CURL
ONE_ARM_CONCENTRATION_CURL
ONE_ARM_PREACHER_CURL
PLATE_PINCH_CURL
PREACHER_CURL_WITH_CABLE
REVERSE_EZ_BAR_CURL
REVERSE_GRIP_BARBELL_BICEPS_CURL
REVERSE_GRIP_WRIST_CURL
SEATED_ALTERNATING_DUMBBELL_BICEPS_CURL
SEATED_DUMBBELL_BICEPS_CURL
SEATED_REVERSE_DUMBBELL_CURL
SPLIT_STANCE_OFFSET_PINKY_DUMBBELL_CURL
STANDING_ALTERNATING_DUMBBELL_CURLS
STANDING_DUMBBELL_BICEPS_CURL
STANDING_EZ_BAR_BICEPS_CURL
STANDING_ZOTTMAN_BICEPS_CURL
STATIC_CURL
SWISS_BALL_DUMBBELL_OVERHEAD_TRICEPS_EXTENSION
SWISS_BALL_EZ_BAR_PREACHER_CURL
TWISTING_STANDING_DUMBBELL_BICEPS_CURL
WIDE_GRIP_EZ_BAR_BICEPS_CURL
```

### DEADLIFT

**23 exercises**

```
BARBELL_DEADLIFT
BARBELL_STRAIGHT_LEG_DEADLIFT
DUMBBELL_DEADLIFT
DUMBBELL_SINGLE_LEG_DEADLIFT_TO_ROW
DUMBBELL_STRAIGHT_LEG_DEADLIFT
KETTLEBELL_DEADLIFT
KETTLEBELL_FLOOR_TO_SHELF
KETTLEBELL_SUMO_DEADLIFT
ONE_ARM_ONE_LEG_DEADLIFT
RACK_PULL
ROMANIAN_DEADLIFT
ROTATIONAL_DUMBBELL_STRAIGHT_LEG_DEADLIFT
SINGLE_ARM_DEADLIFT
SINGLE_LEG_BARBELL_DEADLIFT
SINGLE_LEG_BARBELL_STRAIGHT_LEG_DEADLIFT
SINGLE_LEG_DEADLIFT_WITH_BARBELL
SINGLE_LEG_RDL_CIRCUIT
SINGLE_LEG_ROMANIAN_DEADLIFT_CIRCUIT
SINGLE_LEG_ROMANIAN_DEADLIFT_WITH_DUMBBELL
SUMO_DEADLIFT
SUMO_DEADLIFT_HIGH_PULL
TRAP_BAR_DEADLIFT
WIDE_GRIP_BARBELL_DEADLIFT
```

### ELLIPTICAL

**1 exercises**

```
ELLIPTICAL
```

### FLOOR\_CLIMB

**1 exercises**

```
FLOOR_CLIMB
```

### FLYE

**11 exercises**

```
ARM_ROTATIONS
CABLE_CROSSOVER
DECLINE_DUMBBELL_FLYE
DUMBBELL_FLYE
HUG_A_TREE
INCLINE_DUMBBELL_FLYE
INCLINE_REVERSE_FLYE
KETTLEBELL_FLYE
KNEELING_REAR_FLYE
SINGLE_ARM_STANDING_CABLE_REVERSE_FLYE
SWISS_BALL_DUMBBELL_FLYE
```

### HIP\_RAISE

**48 exercises**

```
BARBELL_HIP_THRUST_ON_FLOOR
BARBELL_HIP_THRUST_WITH_BENCH
BENT_KNEE_SWISS_BALL_REVERSE_HIP_RAISE
BRIDGE_WITH_LEG_EXTENSION
CLAMS
CLAM_BRIDGE
FRONT_KICK_TABLETOP
HIP_EXTENSION_AND_CROSS
HIP_RAISE
HIP_RAISE_WITH_FEET_ON_SWISS_BALL
HIP_RAISE_WITH_HEAD_ON_BOSU_BALL
HIP_RAISE_WITH_HEAD_ON_SWISS_BALL
HIP_RAISE_WITH_KNEE_SQUEEZE
INCLINE_REAR_LEG_EXTENSION
KETTLEBELL_SWING
LEG_CIRCLES
LEG_LIFT
LEG_LIFT_IN_EXTERNAL_ROTATION
MARCHING_HIP_RAISE
MARCHING_HIP_RAISE_WITH_FEET_ON_A_SWISS_BALL
REVERSE_HIP_RAISE
SINGLE_LEG_HIP_RAISE
SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_BENCH
SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_BOSU_BALL
SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_FOAM_ROLLER
SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_MEDICINE_BALL
SINGLE_LEG_HIP_RAISE_WITH_HEAD_ON_BOSU_BALL
SINGLE_LEG_SWISS_BALL_HIP_RAISE_AND_LEG_CURL
WEIGHTED_BENT_KNEE_SWISS_BALL_REVERSE_HIP_RAISE
WEIGHTED_BRIDGE_WITH_LEG_EXTENSION
WEIGHTED_CLAM_BRIDGE
WEIGHTED_FRONT_KICK_TABLETOP
WEIGHTED_HIP_EXTENSION_AND_CROSS
WEIGHTED_HIP_RAISE
WEIGHTED_HIP_RAISE_WITH_FEET_ON_SWISS_BALL
WEIGHTED_HIP_RAISE_WITH_HEAD_ON_BOSU_BALL
WEIGHTED_HIP_RAISE_WITH_HEAD_ON_SWISS_BALL
WEIGHTED_HIP_RAISE_WITH_KNEE_SQUEEZE
WEIGHTED_INCLINE_REAR_LEG_EXTENSION
WEIGHTED_MARCHING_HIP_RAISE
WEIGHTED_MARCHING_HIP_RAISE_WITH_FEET_ON_A_SWISS_BALL
WEIGHTED_REVERSE_HIP_RAISE
WEIGHTED_SINGLE_LEG_HIP_RAISE
WEIGHTED_SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_BENCH
WEIGHTED_SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_BOSU_BALL
WEIGHTED_SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_FOAM_ROLLER
WEIGHTED_SINGLE_LEG_HIP_RAISE_WITH_FOOT_ON_MEDICINE_BALL
WEIGHTED_SINGLE_LEG_HIP_RAISE_WITH_HEAD_ON_BOSU_BALL
```

### HIP\_STABILITY

**35 exercises**

```
BAND_SIDE_LYING_LEG_RAISE
DEAD_BUG
EXTERNAL_HIP_RAISE
FIRE_HYDRANT_KICKS
HIP_CIRCLES
INNER_THIGH_LIFT
LATERAL_WALKS_WITH_BAND_AT_ANKLES
LYING_ABDUCTION_STRETCH
PRETZEL_SIDE_KICK
PRONE_HIP_INTERNAL_ROTATION
QUADRUPED
QUADRUPED_HIP_EXTENSION
QUADRUPED_WITH_LEG_LIFT
SIDE_LYING_LEG_RAISE
SLIDING_HIP_ADDUCTION
STANDING_ADDUCTION
STANDING_CABLE_HIP_ABDUCTION
STANDING_HIP_ABDUCTION
STANDING_REAR_LEG_RAISE
SUPINE_HIP_INTERNAL_ROTATION
WEIGHTED_DEAD_BUG
WEIGHTED_EXTERNAL_HIP_RAISE
WEIGHTED_FIRE_HYDRANT_KICKS
WEIGHTED_HIP_CIRCLES
WEIGHTED_INNER_THIGH_LIFT
WEIGHTED_PRETZEL_SIDE_KICK
WEIGHTED_PRONE_HIP_INTERNAL_ROTATION
WEIGHTED_QUADRUPED_HIP_EXTENSION
WEIGHTED_QUADRUPED_WITH_LEG_LIFT
WEIGHTED_SIDE_LYING_LEG_RAISE
WEIGHTED_SLIDING_HIP_ADDUCTION
WEIGHTED_STANDING_ADDUCTION
WEIGHTED_STANDING_HIP_ABDUCTION
WEIGHTED_STANDING_REAR_LEG_RAISE
WEIGHTED_SUPINE_HIP_INTERNAL_ROTATION
```

### HIP\_SWING

**4 exercises**

```
ONE_ARM_SWING
SINGLE_ARM_DUMBBELL_SWING
SINGLE_ARM_KETTLEBELL_SWING
STEP_OUT_SWING
```

### HYPEREXTENSION

**39 exercises**

```
BACK_EXTENSION_WITH_OPPOSITE_ARM_AND_LEG_REACH
BASE_ROTATIONS
BENT_KNEE_REVERSE_HYPEREXTENSION
COBRA
HOLLOW_HOLD_AND_ROLL
KICKS
KNEELING_SUPERMAN
KNEE_RAISES
LAT_PULL_DOWN_WITH_ROW
MEDICINE_BALL_DEADLIFT_TO_REACH
ONE_ARM_ONE_LEG_ROW
ONE_ARM_ROW_WITH_BAND
OVERHEAD_LUNGE_WITH_MEDICINE_BALL
PLANK_KNEE_TUCKS
SIDE_STEP
SINGLE_LEG_BACK_EXTENSION
SPINE_EXTENSION
STATIC_BACK_EXTENSION
SUPERMAN_FROM_FLOOR
SUPERMAN_ON_SWISS_BALL
SWISS_BALL_BACK_EXTENSION
SWISS_BALL_HYPEREXTENSION
SWISS_BALL_OPPOSITE_ARM_AND_LEG_LIFT
WEIGHTED_BACK_EXTENSION_WITH_OPPOSITE_ARM_AND_LEG_REACH
WEIGHTED_BASE_ROTATIONS
WEIGHTED_BENT_KNEE_REVERSE_HYPEREXTENSION
WEIGHTED_HOLLOW_HOLD_AND_ROLL
WEIGHTED_KICKS
WEIGHTED_KNEELING_SUPERMAN
WEIGHTED_KNEE_RAISES
WEIGHTED_PLANK_KNEE_TUCKS
WEIGHTED_SIDE_STEP
WEIGHTED_SINGLE_LEG_BACK_EXTENSION
WEIGHTED_SPINE_EXTENSION
WEIGHTED_STATIC_BACK_EXTENSION
WEIGHTED_SUPERMAN_FROM_FLOOR
WEIGHTED_SWISS_BALL_BACK_EXTENSION
WEIGHTED_SWISS_BALL_HYPEREXTENSION
WEIGHTED_SWISS_BALL_OPPOSITE_ARM_AND_LEG_LIFT
```

### INDOOR\_BIKE

**3 exercises**

```
AIR_BIKE
ASSAULT_BIKE
STATIONARY_BIKE
```

### LADDER

**2 exercises**

```
AGILITY
SPEED
```

### LATERAL\_RAISE

**36 exercises**

```
ALTERNATING_LATERAL_RAISE_WITH_STATIC_HOLD
ARM_CIRCLES
BAR_MUSCLE_UP
BENT_OVER_LATERAL_RAISE
CABLE_DIAGONAL_RAISE
CABLE_FRONT_RAISE
CALORIE_ROW
COMBO_SHOULDER_RAISE
DUMBBELL_DIAGONAL_RAISE
DUMBBELL_LATERAL_RAISE
DUMBBELL_V_RAISE
LEANING_DUMBBELL_LATERAL_RAISE
LYING_DUMBBELL_RAISE
MUSCLE_UP
ONE_ARM_CABLE_LATERAL_RAISE
OVERHAND_GRIP_REAR_LATERAL_RAISE
PLATE_RAISES
RING_DIP
RING_DIP_KIPPING
RING_MUSCLE_UP
ROPE_CLIMB
SCAPTION
SEATED_LATERAL_RAISE
SEATED_REAR_LATERAL_RAISE
SHAVING_THE_HEAD
SIDE_LYING_LATERAL_RAISE
STANDING_LIFT
SUSPENDED_ROW
UNDERHAND_GRIP_REAR_LATERAL_RAISE
WALL_SLIDE
WALL_WALK
WEIGHTED_RING_DIP
WEIGHTED_RING_MUSCLE_UP
WEIGHTED_ROPE_CLIMB
WEIGHTED_WALL_SLIDE
_45_DEGREE_CABLE_EXTERNAL_ROTATION
```

### LEG\_CURL

**14 exercises**

```
BAND_GOOD_MORNING
BAR_GOOD_MORNING
GOOD_MORNING
LEG_CURL
SEATED_BARBELL_GOOD_MORNING
SINGLE_LEG_BARBELL_GOOD_MORNING
SINGLE_LEG_SLIDING_LEG_CURL
SLIDING_LEG_CURL
SPLIT_BARBELL_GOOD_MORNING
SPLIT_STANCE_EXTENSION
STAGGERED_STANCE_GOOD_MORNING
SWISS_BALL_HIP_RAISE_AND_LEG_CURL
WEIGHTED_LEG_CURL
ZERCHER_GOOD_MORNING
```

### LEG\_RAISE

**22 exercises**

```
HANGING_KNEE_RAISE
HANGING_LEG_RAISE
HANGING_SINGLE_LEG_RAISE
KETTLEBELL_LEG_RAISES
LATERAL_STEPOVER
LEG_LOWERING_DRILL
LYING_STRAIGHT_LEG_RAISE
MEDICINE_BALL_LEG_DROPS
QUADRUPED_LEG_RAISE
REVERSE_LEG_RAISE
REVERSE_LEG_RAISE_ON_SWISS_BALL
SINGLE_LEG_LOWERING_DRILL
WEIGHTED_HANGING_KNEE_RAISE
WEIGHTED_HANGING_LEG_RAISE
WEIGHTED_HANGING_SINGLE_LEG_RAISE
WEIGHTED_LATERAL_STEPOVER
WEIGHTED_LEG_LOWERING_DRILL
WEIGHTED_LYING_STRAIGHT_LEG_RAISE
WEIGHTED_QUADRUPED_LEG_RAISE
WEIGHTED_REVERSE_LEG_RAISE
WEIGHTED_REVERSE_LEG_RAISE_ON_SWISS_BALL
WEIGHTED_SINGLE_LEG_LOWERING_DRILL
```

### LUNGE

**90 exercises**

```
ALTERNATING_BARBELL_FORWARD_LUNGE
ALTERNATING_DUMBBELL_LUNGE
ALTERNATING_DUMBBELL_LUNGE_WITH_REACH
BACK_FOOT_ELEVATED_DUMBBELL_SPLIT_SQUAT
BARBELL_BOX_LUNGE
BARBELL_BULGARIAN_SPLIT_SQUAT
BARBELL_CROSSOVER_LUNGE
BARBELL_FRONT_SPLIT_SQUAT
BARBELL_LUNGE
BARBELL_REVERSE_LUNGE
BARBELL_SIDE_LUNGE
BARBELL_SPLIT_SQUAT
CORE_CONTROL_REAR_LUNGE
CURTSY_LUNGE
DIAGONAL_LUNGE
DROP_LUNGE
DUMBBELL_BOX_LUNGE
DUMBBELL_BULGARIAN_SPLIT_SQUAT
DUMBBELL_CROSSOVER_LUNGE
DUMBBELL_DIAGONAL_LUNGE
DUMBBELL_LUNGE
DUMBBELL_LUNGE_AND_ROTATION
DUMBBELL_OVERHEAD_BULGARIAN_SPLIT_SQUAT
DUMBBELL_OVERHEAD_WALKING_LUNGE
DUMBBELL_REVERSE_LUNGE
DUMBBELL_REVERSE_LUNGE_TO_HIGH_KNEE_AND_PRESS
DUMBBELL_SIDE_LUNGE
ELEVATED_FRONT_FOOT_BARBELL_SPLIT_SQUAT
FRONT_FOOT_ELEVATED_DUMBBELL_SPLIT_SQUAT
GUNSLINGER_LUNGE
LAWNMOWER_LUNGE
LOW_LUNGE_WITH_ISOMETRIC_ADDUCTION
LOW_SIDE_TO_SIDE_LUNGE
LUNGE_MATRIX
LUNGE_WITH_ARM_REACH
LUNGE_WITH_DIAGONAL_REACH
LUNGE_WITH_SIDE_BEND
OFFSET_DUMBBELL_LUNGE
OFFSET_DUMBBELL_REVERSE_LUNGE
OVERHEAD_BULGARIAN_SPLIT_SQUAT
OVERHEAD_DUMBBELL_LUNGE
OVERHEAD_DUMBBELL_REVERSE_LUNGE
OVERHEAD_DUMBBELL_SPLIT_SQUAT
OVERHEAD_LUNGE
OVERHEAD_LUNGE_WITH_ROTATION
REVERSE_BARBELL_BOX_LUNGE
REVERSE_BOX_LUNGE
REVERSE_DUMBBELL_BOX_LUNGE
REVERSE_DUMBBELL_CROSSOVER_LUNGE
REVERSE_DUMBBELL_DIAGONAL_LUNGE
REVERSE_LUNGE_WITH_REACH_BACK
REVERSE_LUNGE_WITH_TWIST_AND_OVERHEAD_REACH
REVERSE_SLIDING_BOX_LUNGE
REVERSE_SLIDING_LUNGE
RUNNERS_LUNGE_TO_BALANCE
SCISSOR_POWER_SWITCH
SHIFTING_SIDE_LUNGE
SIDE_AND_CROSSOVER_LUNGE
SIDE_LUNGE
SIDE_LUNGE_AND_PRESS
SIDE_LUNGE_JUMP_OFF
SIDE_LUNGE_SWEEP
SIDE_LUNGE_TO_CROSSOVER_TAP
SIDE_TO_SIDE_LUNGE_CHOPS
SIFF_JUMP_LUNGE
SINGLE_ARM_REVERSE_LUNGE_AND_PRESS
SLIDING_LATERAL_LUNGE
WALKING_BARBELL_LUNGE
WALKING_DUMBBELL_LUNGE
WALKING_LUNGE
WEIGHTED_CURTSY_LUNGE
WEIGHTED_LUNGE
WEIGHTED_LUNGE_MATRIX
WEIGHTED_REVERSE_LUNGE_WITH_REACH_BACK
WEIGHTED_REVERSE_LUNGE_WITH_TWIST_AND_OVERHEAD_REACH
WEIGHTED_REVERSE_SLIDING_BOX_LUNGE
WEIGHTED_REVERSE_SLIDING_LUNGE
WEIGHTED_RUNNERS_LUNGE_TO_BALANCE
WEIGHTED_SHIFTING_SIDE_LUNGE
WEIGHTED_SIDE_AND_CROSSOVER_LUNGE
WEIGHTED_SIDE_LUNGE
WEIGHTED_SIDE_LUNGE_AND_PRESS
WEIGHTED_SIDE_LUNGE_JUMP_OFF
WEIGHTED_SIDE_LUNGE_SWEEP
WEIGHTED_SIDE_LUNGE_TO_CROSSOVER_TAP
WEIGHTED_SIDE_TO_SIDE_LUNGE_CHOPS
WEIGHTED_SIFF_JUMP_LUNGE
WEIGHTED_SLIDING_LATERAL_LUNGE
WEIGHTED_WALKING_LUNGE
WIDE_GRIP_OVERHEAD_BARBELL_SPLIT_SQUAT
```

### MOVE

**64 exercises**

```
ARCH_AND_CURL
ARM_CIRCLES_WITH_BALL_BAND_AND_WEIGHT
ARM_STRETCH
BACK_MASSAGE
BELLY_BREATHING
BRIDGE_WITH_BALL
DIAMOND_LEG_CRUNCH
DIAMOND_LEG_LIFT
EIGHT_POINT_SHOULDER_OPENER
FOOTWORK
FOOTWORK_ON_DISC
FOOT_ROLLING
FORWARD_FOLD
FROG_WITH_BAND
HALF_ROLL_UP
HAMSTRING_STRETCH
HIP_STRETCH
HUG_A_TREE_WITH_BALL_BAND_AND_WEIGHT
KNEE_CIRCLES
KNEE_FOLDS_ON_DISC
LATERAL_FLEXION
LEG_STRETCH_WITH_BAND
LEG_STRETCH_WITH_LEG_CIRCLES
LOWER_LIFT_ON_DISC
LUNGES_WITH_KNEE_LIFT
LUNGE_SQUAT
MERMAID_STRETCH
NEUTRAL_PELVIC_POSITION
PELVIC_CLOCKS_ON_DISC
PILATES_PLIE_SQUATS_PARALLEL_TURNED_OUT_FLAT_AND_HEELS_WITH_CHAIR
PIRIFORMIS_STRETCH
PLANK_KNEE_CROSSES
PLANK_KNEE_PULLS
PLANK_UP_DOWNS
PRAYER_MUDRA
PSOAS_LUNGE_STRETCH
RIBCAGE_BREATHING
ROLL_DOWN
ROLL_UP_WITH_WEIGHT_AND_BAND
SAW
SCAPULAR_STABILIZATION
SCISSORS_ON_DISC
SEATED_HIP_STRETCHUP
SEATED_TWIST
SHAVING_THE_HEAD_WITH_BALL_BAND_AND_WEIGHT
SPINAL_TWIST
SPINAL_TWIST_STRETCH
SPINE_STRETCH_FORWARD
SQUATS_WITH_BALL
STANDING_SIDE_STRETCH
STANDING_SINGLE_LEG_FORWARD_BEND_WITH_IT_BAND_OPENER
STAND_AND_HANG
STRAIGHT_LEG_CRUNCH_WITH_LEGS_CROSSED
STRAIGHT_LEG_CRUNCH_WITH_LEGS_CROSSED_WITH_BALL
STRAIGHT_LEG_CRUNCH_WITH_LEG_LIFT
STRAIGHT_LEG_CRUNCH_WITH_LEG_LIFT_WITH_BALL
STRAIGHT_LEG_DIAGONAL_CRUNCH
STRAIGHT_LEG_DIAGONAL_CRUNCH_WITH_BALL
TAILBONE_CURL
THROAT_LOCK
TICK_TOCK_SIDE_ROLL
TWIST
V_LEG_CRUNCHES
V_SIT
```

### OLYMPIC\_LIFT

**28 exercises**

```
BARBELL_HANG_POWER_CLEAN
BARBELL_HANG_POWER_SNATCH
BARBELL_HANG_PULL
BARBELL_HANG_SQUAT_CLEAN
BARBELL_HIGH_PULL
BARBELL_POWER_CLEAN
BARBELL_POWER_SNATCH
BARBELL_SNATCH
BARBELL_SPLIT_JERK
BARBELL_SQUAT_CLEAN
CLEAN
CLEAN_AND_JERK
CLEAN_AND_PRESS
DUMBBELL_CLEAN
DUMBBELL_HANG_PULL
DUMBBELL_HANG_SNATCH
DUMBBELL_POWER_CLEAN_AND_JERK
DUMBBELL_POWER_CLEAN_AND_PUSH_PRESS
DUMBBELL_POWER_CLEAN_AND_STRICT_PRESS
DUMBBELL_SNATCH
MEDICINE_BALL_CLEAN
ONE_HAND_DUMBBELL_SPLIT_SNATCH
PUSH_JERK
SINGLE_ARM_DUMBBELL_SNATCH
SINGLE_ARM_HANG_SNATCH
SINGLE_ARM_KETTLEBELL_SNATCH
SPLIT_JERK
SQUAT_CLEAN_AND_JERK
```

### PLANK

**134 exercises**

```
BEAR_CRAWL
BRIDGE_ONE_LEG_BRIDGE
BRIDGE_WITH_GLUTE_LOWER_LIFT
CROSS_BODY_MOUNTAIN_CLIMBER
ELBOW_PLANK_PIKE_JACKS
ELEVATED_FEET_PLANK
ELEVATOR_ABS
EXTENDED_PLANK
FULL_PLANK_PASSE_TWIST
INCHING_ELBOW_PLANK
INCHWORM_TO_SIDE_PLANK
KNEELING_PLANK
KNEELING_SIDE_PLANK_WITH_LEG_LIFT
LATERAL_ROLL
LYING_REVERSE_PLANK
MEDICINE_BALL_MOUNTAIN_CLIMBER
MODIFIED_MOUNTAIN_CLIMBER_AND_EXTENSION
MOUNTAIN_CLIMBER
MOUNTAIN_CLIMBER_ON_SLIDING_DISCS
MOUNTAIN_CLIMBER_WITH_FEET_ON_BOSU_BALL
MOUNTAIN_CLIMBER_WITH_HANDS_ON_BENCH
MOUNTAIN_CLIMBER_WITH_HANDS_ON_SWISS_BALL
PLANK_JACKS_WITH_FEET_ON_SLIDING_DISCS
PLANK_KNEE_TWIST
PLANK_PIKES
PLANK_PIKE_JUMPS
PLANK_TO_STAND_UP
PLANK_WITH_ARM_RAISE
PLANK_WITH_ARM_VARIATIONS
PLANK_WITH_FEET_ON_SWISS_BALL
PLANK_WITH_KNEE_TO_ELBOW
PLANK_WITH_LEG_LIFT
PLANK_WITH_OBLIQUE_CRUNCH
PLYOMETRIC_SIDE_PLANK
REVERSE_PLANK_WITH_LEG_PULL
RING_PLANK_SPRAWLS
ROLLING_SIDE_PLANK
SIDE_KICK_PLANK
SIDE_PLANK
SIDE_PLANK_AND_ROW
SIDE_PLANK_LIFT
SIDE_PLANK_TO_PLANK_WITH_REACH_UNDER
SIDE_PLANK_WITH_ELBOW_ON_BOSU_BALL
SIDE_PLANK_WITH_FEET_ON_BENCH
SIDE_PLANK_WITH_KNEE_CIRCLE
SIDE_PLANK_WITH_KNEE_TUCK
SIDE_PLANK_WITH_LEG_LIFT
SIDE_PLANK_WITH_REACH_UNDER
SINGLE_LEG_ELEVATED_FEET_PLANK
SINGLE_LEG_FLEX_AND_EXTEND
SINGLE_LEG_SIDE_PLANK
SPIDERMAN_PLANK
STRAIGHT_ARM_PLANK
STRAIGHT_ARM_PLANK_WITH_SHOULDER_TOUCH
SWISS_BALL_PLANK
SWISS_BALL_PLANK_LEG_LIFT
SWISS_BALL_PLANK_LEG_LIFT_AND_HOLD
SWISS_BALL_PLANK_WITH_FEET_ON_BENCH
SWISS_BALL_PRONE_JACKKNIFE
SWISS_BALL_SIDE_PLANK
THREE_WAY_PLANK
TOWEL_PLANK_AND_KNEE_IN
TURKISH_GET_UP_TO_SIDE_PLANK
TWO_POINT_PLANK
T_STABILIZATION
WEIGHTED_45_DEGREE_PLANK
WEIGHTED_90_DEGREE_STATIC_HOLD
WEIGHTED_BEAR_CRAWL
WEIGHTED_CROSS_BODY_MOUNTAIN_CLIMBER
WEIGHTED_ELBOW_PLANK_PIKE_JACKS
WEIGHTED_ELEVATED_FEET_PLANK
WEIGHTED_ELEVATOR_ABS
WEIGHTED_EXTENDED_PLANK
WEIGHTED_FULL_PLANK_PASSE_TWIST
WEIGHTED_INCHING_ELBOW_PLANK
WEIGHTED_INCHWORM_TO_SIDE_PLANK
WEIGHTED_KNEELING_PLANK
WEIGHTED_KNEELING_SIDE_PLANK_WITH_LEG_LIFT
WEIGHTED_LATERAL_ROLL
WEIGHTED_LYING_REVERSE_PLANK
WEIGHTED_MEDICINE_BALL_MOUNTAIN_CLIMBER
WEIGHTED_MODIFIED_MOUNTAIN_CLIMBER_AND_EXTENSION
WEIGHTED_MOUNTAIN_CLIMBER
WEIGHTED_MOUNTAIN_CLIMBER_ON_SLIDING_DISCS
WEIGHTED_MOUNTAIN_CLIMBER_WITH_FEET_ON_BOSU_BALL
WEIGHTED_MOUNTAIN_CLIMBER_WITH_HANDS_ON_BENCH
WEIGHTED_MOUNTAIN_CLIMBER_WITH_HANDS_ON_SWISS_BALL
WEIGHTED_PLANK
WEIGHTED_PLANK_JACKS_WITH_FEET_ON_SLIDING_DISCS
WEIGHTED_PLANK_KNEE_TWIST
WEIGHTED_PLANK_PIKES
WEIGHTED_PLANK_PIKE_JUMPS
WEIGHTED_PLANK_TO_STAND_UP
WEIGHTED_PLANK_WITH_ARM_RAISE
WEIGHTED_PLANK_WITH_KNEE_TO_ELBOW
WEIGHTED_PLANK_WITH_OBLIQUE_CRUNCH
WEIGHTED_PLYOMETRIC_SIDE_PLANK
WEIGHTED_ROLLING_SIDE_PLANK
WEIGHTED_SIDE_KICK_PLANK
WEIGHTED_SIDE_PLANK
WEIGHTED_SIDE_PLANK_AND_ROW
WEIGHTED_SIDE_PLANK_LIFT
WEIGHTED_SIDE_PLANK_WITH_ELBOW_ON_BOSU_BALL
WEIGHTED_SIDE_PLANK_WITH_FEET_ON_BENCH
WEIGHTED_SIDE_PLANK_WITH_KNEE_CIRCLE
WEIGHTED_SIDE_PLANK_WITH_KNEE_TUCK
WEIGHTED_SIDE_PLANK_WITH_LEG_LIFT
WEIGHTED_SIDE_PLANK_WITH_REACH_UNDER
WEIGHTED_SINGLE_LEG_ELEVATED_FEET_PLANK
WEIGHTED_SINGLE_LEG_FLEX_AND_EXTEND
WEIGHTED_SINGLE_LEG_SIDE_PLANK
WEIGHTED_SPIDERMAN_PLANK
WEIGHTED_STRAIGHT_ARM_PLANK
WEIGHTED_STRAIGHT_ARM_PLANK_WITH_SHOULDER_TOUCH
WEIGHTED_SWISS_BALL_PLANK
WEIGHTED_SWISS_BALL_PLANK_LEG_LIFT
WEIGHTED_SWISS_BALL_PLANK_LEG_LIFT_AND_HOLD
WEIGHTED_SWISS_BALL_PLANK_WITH_FEET_ON_BENCH
WEIGHTED_SWISS_BALL_PRONE_JACKKNIFE
WEIGHTED_SWISS_BALL_SIDE_PLANK
WEIGHTED_THREE_WAY_PLANK
WEIGHTED_TOWEL_PLANK_AND_KNEE_IN
WEIGHTED_TURKISH_GET_UP_TO_SIDE_PLANK
WEIGHTED_TWO_POINT_PLANK
WEIGHTED_T_STABILIZATION
WEIGHTED_WIDE_STANCE_PLANK_WITH_DIAGONAL_ARM_LIFT
WEIGHTED_WIDE_STANCE_PLANK_WITH_DIAGONAL_LEG_LIFT
WEIGHTED_WIDE_STANCE_PLANK_WITH_LEG_LIFT
WIDE_STANCE_PLANK_WITH_DIAGONAL_ARM_LIFT
WIDE_STANCE_PLANK_WITH_DIAGONAL_LEG_LIFT
WIDE_STANCE_PLANK_WITH_LEG_LIFT
WIDE_STANCE_PLANK_WITH_OPPOSITE_ARM_AND_LEG_LIFT
_45_DEGREE_PLANK
_90_DEGREE_STATIC_HOLD
```

### PLYO

**38 exercises**

```
ALTERNATING_JUMP_LUNGE
BARBELL_JUMP_SQUAT
BODY_WEIGHT_JUMP_SQUAT
BOX_JUMP
BOX_JUMP_OVERS
BOX_JUMP_OVERS_OVER_THE_BOX
CROSS_KNEE_STRIKE
DEPTH_JUMP
DUMBBELL_JUMP_SQUAT
DUMBBELL_SPLIT_JUMP
FRONT_KNEE_STRIKE
HIGH_BOX_JUMP
ISOMETRIC_EXPLOSIVE_BODY_WEIGHT_JUMP_SQUAT
JUMP_SQUAT
LATERAL_LEAP_AND_HOP
LATERAL_PLYO_SQUATS
LATERAL_SLIDE
MEDICINE_BALL_OVERHEAD_THROWS
MEDICINE_BALL_SIDE_THROW
MEDICINE_BALL_SLAM
SIDE_TO_SIDE_MEDICINE_BALL_THROWS
SIDE_TO_SIDE_SHUFFLE_JUMP
SQUAT_JUMPS_IN_AND_OUT
SQUAT_JUMP_ONTO_BOX
STAR_JUMP_SQUATS
WEIGHTED_ALTERNATING_JUMP_LUNGE
WEIGHTED_CROSS_KNEE_STRIKE
WEIGHTED_DEPTH_JUMP
WEIGHTED_FRONT_KNEE_STRIKE
WEIGHTED_HIGH_BOX_JUMP
WEIGHTED_ISOMETRIC_EXPLOSIVE_JUMP_SQUAT
WEIGHTED_JUMP_SQUAT
WEIGHTED_LATERAL_LEAP_AND_HOP
WEIGHTED_LATERAL_PLYO_SQUATS
WEIGHTED_LATERAL_SLIDE
WEIGHTED_SIDE_TO_SIDE_SHUFFLE_JUMP
WEIGHTED_SQUAT_JUMPS_IN_AND_OUT
WEIGHTED_SQUAT_JUMP_ONTO_BOX
```

### POSE

**85 exercises**

```
ALL_FOURS
ANKLE_TO_KNEE
BABY_COBRA
BOAT
BOUND_ANGLE
BOUND_SEATED_SINGLE_LEG_FORWARD_BEND
BOW
BOWED_HALF_MOON
BRIDGE
CAT
CHAIR
CHILDS
CORPSE
COW
COW_FACE
DEVOTIONAL_WARRIOR
DOLPHIN
DOLPHIN_PLANK
DOWNWARD_FACING_DOG
DOWN_DOG_KNEE_TO_NOSE
DOWN_DOG_SPLIT
DOWN_DOG_SPLIT_OPEN_HIP_BENT_KNEE
EAGLE
EASY_SEATED
EXTENDED_PUPPY
EXTENDED_SIDE_ANGLE
FISH
FOUR_LIMBED_STAFF
FULL_SPLIT
GATE
HALF_CHAIR_HALF_ANKLE_TO_KNEE
HALF_MOON
HEAD_TO_KNEE
HERON
HEROS
HIGH_LUNGE
KNEES_CHEST_CHIN
LIZARD
LOCUST
LOW_LUNGE
LOW_LUNGE_TWIST
LOW_LUNGE_WITH_KNEE_DOWN
MERMAID
MOUNTAIN
ONE_LEGGED_DOWNWARD_FACING_POSE_OPEN_HIP_BENT_KNEE
ONE_LEGGED_PIGEON
PEACEFUL_WARRIOR
PLOW
RECLINED_HAND_TO_FOOT
REVOLVED_HALF_MOON
REVOLVED_HEAD_TO_KNEE
REVOLVED_TRIANGLE
RUNNERS_LUNGE
SEATED_EASY_SIDE_BEND
SEATED_EASY_TWIST
SEATED_LONG_LEG_FORWARD_BEND
SEATED_WIDE_LEG_FORWARD_BEND
SHOULDER_STAND
SIDE_BOAT
SPHINX
SQUAT_OPEN_ARM_TWIST
SQUAT_PALM_PRESS
STAFF
STANDING_ARMS_UP
STANDING_FORWARD_BEND
STANDING_FORWARD_BEND_HALFWAY_UP
STANDING_SIDE_OPENER
STANDING_SINGLE_LEG_FORWARD_BEND
STANDING_SPLIT
STANDING_WIDE_LEG_FORWARD_BEND
STANDING_WIDE_LEG_FORWARD_BEND_WITH_TWIST
SUPINE_SPINAL_TWIST
TABLE_TOP
THREAD_THE_NEEDLE
THUNDERBOLT
THUNDERBOLT_POSE_BOTH_SIDES_ARM_STRETCH
TREE
TRIANGLE
UPWARD_FACING_PLANK
UP_DOG
WARRIOR_ONE
WARRIOR_THREE
WARRIOR_TWO
WHEEL
WIDE_SIDE_LUNGE
```

### PULL\_UP

**46 exercises**

```
BANDED_PULL_UPS
BAND_ASSISTED_CHIN_UP
BAND_ASSISTED_PULL_UP
BURPEE_PULL_UP
CHIN_UP
CLOSE_GRIP_CHIN_UP
CLOSE_GRIP_LAT_PULLDOWN
CROSSOVER_CHIN_UP
EZ_BAR_PULLOVER
HANGING_HURDLE
JUMPING_PULL_UPS
KIPPING_PULL_UP
KNEELING_LAT_PULLDOWN
KNEELING_UNDERHAND_GRIP_LAT_PULLDOWN
LAT_PULLDOWN
L_PULL_UP
MIXED_GRIP_CHIN_UP
MIXED_GRIP_PULL_UP
NEUTRAL_GRIP_CHIN_UP
NEUTRAL_GRIP_PULL_UP
PULL_UP
REVERSE_GRIP_PULLDOWN
STANDING_CABLE_PULLOVER
STRAIGHT_ARM_PULLDOWN
SUSPENDED_CHIN_UP
SWISS_BALL_EZ_BAR_PULLOVER
TOWEL_PULL_UP
WEIGHTED_BURPEE_PULL_UP
WEIGHTED_CHIN_UP
WEIGHTED_CLOSE_GRIP_CHIN_UP
WEIGHTED_CROSSOVER_CHIN_UP
WEIGHTED_HANGING_HURDLE
WEIGHTED_JUMPING_PULL_UPS
WEIGHTED_KIPPING_PULL_UP
WEIGHTED_L_PULL_UP
WEIGHTED_MIXED_GRIP_CHIN_UP
WEIGHTED_MIXED_GRIP_PULL_UP
WEIGHTED_NEUTRAL_GRIP_CHIN_UP
WEIGHTED_NEUTRAL_GRIP_PULL_UP
WEIGHTED_PULL_UP
WEIGHTED_SUSPENDED_CHIN_UP
WEIGHTED_TOWEL_PULL_UP
WEIGHTED_WIDE_GRIP_PULL_UP
WIDE_GRIP_LAT_PULLDOWN
WIDE_GRIP_PULL_UP
_30_DEGREE_LAT_PULLDOWN
```

### PUSH\_UP

**90 exercises**

```
ALTERNATING_HANDS_MEDICINE_BALL_PUSH_UP
ALTERNATING_STAGGERED_PUSH_UP
BICEPS_PUSH_UP
BOSU_BALL_PUSH_UP
CHEST_PRESS_WITH_BAND
CLAPPING_PUSH_UP
CLOSE_GRIP_MEDICINE_BALL_PUSH_UP
CLOSE_HANDS_PUSH_UP
DECLINE_PUSH_UP
DIAMOND_PUSH_UP
DYNAMIC_PUSH_UP
EXPLOSIVE_CROSSOVER_PUSH_UP
EXPLOSIVE_PUSH_UP
FEET_ELEVATED_SIDE_TO_SIDE_PUSH_UP
HANDSTAND_PUSH_UP
HAND_RELEASE_PUSH_UP
HINDU_PUSH_UP
INCLINE_PUSH_UP
ISOMETRIC_EXPLOSIVE_PUSH_UP
JUDO_PUSH_UP
KIPPING_HANDSTAND_PUSH_UP
KIPPING_PARALLETTE_HANDSTAND_PUSH_UP
KNEELING_PUSH_UP
MEDICINE_BALL_CHEST_PASS
MEDICINE_BALL_PUSH_UP
ONE_ARM_PUSH_UP
PARALLETTE_HANDSTAND_PUSH_UP
PIKE_PUSH_UP
PILATES_PUSHUP
PUSH_UP
PUSH_UP_AND_ROW
PUSH_UP_PLUS
PUSH_UP_WITH_FEET_ON_SWISS_BALL
PUSH_UP_WITH_ONE_HAND_ON_MEDICINE_BALL
RING_HANDSTAND_PUSH_UP
RING_PUSH_UP
SHOULDER_PUSH_UP
SHOULDER_TAPPING_PUSH_UP
SINGLE_ARM_MEDICINE_BALL_PUSH_UP
SPIDERMAN_PUSH_UP
STACKED_FEET_PUSH_UP
STAGGERED_HANDS_PUSH_UP
SUSPENDED_PUSH_UP
SWISS_BALL_PUSH_UP
SWISS_BALL_PUSH_UP_PLUS
TRIPLE_STOP_PUSH_UP
T_PUSH_UP
WEIGHTED_ALTERNATING_HANDS_MEDICINE_BALL_PUSH_UP
WEIGHTED_ALTERNATING_STAGGERED_PUSH_UP
WEIGHTED_BICEPS_PUSH_UP
WEIGHTED_BOSU_BALL_PUSH_UP
WEIGHTED_CLAPPING_PUSH_UP
WEIGHTED_CLOSE_GRIP_MEDICINE_BALL_PUSH_UP
WEIGHTED_CLOSE_HANDS_PUSH_UP
WEIGHTED_DECLINE_PUSH_UP
WEIGHTED_DIAMOND_PUSH_UP
WEIGHTED_EXPLOSIVE_CROSSOVER_PUSH_UP
WEIGHTED_EXPLOSIVE_PUSH_UP
WEIGHTED_FEET_ELEVATED_SIDE_TO_SIDE_PUSH_UP
WEIGHTED_HANDSTAND_PUSH_UP
WEIGHTED_HAND_RELEASE_PUSH_UP
WEIGHTED_HINDU_PUSH_UP
WEIGHTED_INCLINE_PUSH_UP
WEIGHTED_ISOMETRIC_EXPLOSIVE_PUSH_UP
WEIGHTED_JUDO_PUSH_UP
WEIGHTED_KNEELING_PUSH_UP
WEIGHTED_MEDICINE_BALL_PUSH_UP
WEIGHTED_ONE_ARM_PUSH_UP
WEIGHTED_PARALLETTE_HANDSTAND_PUSH_UP
WEIGHTED_PIKE_PUSH_UP
WEIGHTED_PUSH_UP
WEIGHTED_PUSH_UP_AND_ROW
WEIGHTED_PUSH_UP_PLUS
WEIGHTED_PUSH_UP_WITH_FEET_ON_SWISS_BALL
WEIGHTED_PUSH_UP_WITH_ONE_HAND_ON_MEDICINE_BALL
WEIGHTED_RING_HANDSTAND_PUSH_UP
WEIGHTED_RING_PUSH_UP
WEIGHTED_SHOULDER_PUSH_UP
WEIGHTED_SINGLE_ARM_MEDICINE_BALL_PUSH_UP
WEIGHTED_SPIDERMAN_PUSH_UP
WEIGHTED_STACKED_FEET_PUSH_UP
WEIGHTED_STAGGERED_HANDS_PUSH_UP
WEIGHTED_SUSPENDED_PUSH_UP
WEIGHTED_SWISS_BALL_PUSH_UP
WEIGHTED_SWISS_BALL_PUSH_UP_PLUS
WEIGHTED_TRIPLE_STOP_PUSH_UP
WEIGHTED_T_PUSH_UP
WEIGHTED_WIDE_HANDS_PUSH_UP
WIDE_GRIP_PUSH_UP
WIDE_HANDS_PUSH_UP
```

### ROW

**50 exercises**

```
ALTERNATING_DUMBBELL_ROW
BANDED_FACE_PULLS
BARBELL_ROW
BARBELL_STRAIGHT_LEG_DEADLIFT_TO_ROW
BENT_OVER_ROW_WITH_BARBELL
BENT_OVER_ROW_WITH_DUMBELL
CABLE_ROW_STANDING
CHEST_SUPPORTED_DUMBBELL_ROW
DECLINE_RING_ROW
DUMBBELL_ROW
ELEVATED_FEET_INVERTED_ROW
ELEVATED_RING_ROW
FACE_PULL
FACE_PULL_WITH_EXTERNAL_ROTATION
INDOOR_ROW
INVERTED_ROW
INVERTED_ROW_WITH_FEET_ON_SWISS_BALL
KETTLEBELL_ROW
MODIFIED_INVERTED_ROW
NEUTRAL_GRIP_ALTERNATING_DUMBBELL_ROW
ONE_ARM_BENT_OVER_ROW
ONE_LEGGED_DUMBBELL_ROW
RENEGADE_ROW
REVERSE_GRIP_BARBELL_ROW
RING_ROW
ROPE_HANDLE_CABLE_ROW
SEATED_CABLE_ROW
SEATED_DUMBBELL_ROW
SEATED_UNDERHAND_GRIP_CABLE_ROW
SINGLE_ARM_CABLE_ROW
SINGLE_ARM_CABLE_ROW_AND_ROTATION
SINGLE_ARM_INVERTED_ROW
SINGLE_ARM_NEUTRAL_GRIP_DUMBBELL_ROW
SINGLE_ARM_NEUTRAL_GRIP_DUMBBELL_ROW_AND_ROTATION
SUSPENDED_INVERTED_ROW
TOWEL_GRIP_INVERTED_ROW
TRX_INVERTED_ROW
T_BAR_ROW
UNDERHAND_GRIP_CABLE_ROW
V_GRIP_CABLE_ROW
WEIGHTED_ELEVATED_FEET_INVERTED_ROW
WEIGHTED_INVERTED_ROW
WEIGHTED_INVERTED_ROW_WITH_FEET_ON_SWISS_BALL
WEIGHTED_MODIFIED_INVERTED_ROW
WEIGHTED_ROW
WEIGHTED_SINGLE_ARM_INVERTED_ROW
WEIGHTED_SUSPENDED_INVERTED_ROW
WEIGHTED_TOWEL_GRIP_INVERTED_ROW
WEIGHTED_TRX_INVERTED_ROW
WIDE_GRIP_SEATED_CABLE_ROW
```

### RUN

**5 exercises**

```
JOG
RUN
RUN_OR_WALK
SPRINT
WALK
```

### RUN\_INDOOR

**2 exercises**

```
INDOOR_TRACK_RUN
TREADMILL
```

### SANDBAG

**12 exercises**

```
AROUND_THE_WORLD
BACK_SQUAT
BEAR_CRAWL_PULL_THROUGH
BEAR_HUG_SQUAT
FRONT_CARRY
FRONT_SQUAT
OVERHEAD_PRESS
PLANK_PULL_THROUGH
ROTATIONAL_LUNGE
SHOULDERING
SHOVELING
ZERCHER_SQUAT
```

### SHOULDER\_PRESS

**28 exercises**

```
ALTERNATING_DUMBBELL_SHOULDER_PRESS
ARNOLD_PRESS
BARBELL_FRONT_SQUAT_TO_PUSH_PRESS
BARBELL_PUSH_PRESS
BARBELL_SHOULDER_PRESS
DEAD_CURL_PRESS
DUMBBELL_ALTERNATING_SHOULDER_PRESS_AND_TWIST
DUMBBELL_FRONT_RAISE
DUMBBELL_HAMMER_CURL_TO_LUNGE_TO_PRESS
DUMBBELL_PUSH_PRESS
DUMBBELL_SHOULDER_PRESS
FLOOR_INVERTED_SHOULDER_PRESS
INVERTED_SHOULDER_PRESS
MILITARY_PRESS
ONE_ARM_PUSH_PRESS
OVERHEAD_BARBELL_PRESS
OVERHEAD_DUMBBELL_PRESS
SEATED_BARBELL_SHOULDER_PRESS
SEATED_DUMBBELL_SHOULDER_PRESS
SINGLE_ARM_DUMBBELL_SHOULDER_PRESS
SINGLE_ARM_STEP_UP_AND_PRESS
SMITH_MACHINE_OVERHEAD_PRESS
SPLIT_STANCE_HAMMER_CURL_TO_PRESS
STRICT_PRESS
SWISS_BALL_DUMBBELL_SHOULDER_PRESS
WEIGHTED_FLOOR_INVERTED_SHOULDER_PRESS
WEIGHTED_INVERTED_SHOULDER_PRESS
WEIGHT_PLATE_FRONT_RAISE
```

### SHOULDER\_STABILITY

**36 exercises**

```
BAND_EXTERNAL_ROTATION
BAND_INTERNAL_ROTATION
BENT_ARM_LATERAL_RAISE_AND_EXTERNAL_ROTATION
CABLE_EXTERNAL_ROTATION
CABLE_INTERNAL_ROTATION
DUMBBELL_FACE_PULL_WITH_EXTERNAL_ROTATION
FLOOR_I_RAISE
FLOOR_T_RAISE
FLOOR_Y_RAISE
INCLINE_I_RAISE
INCLINE_L_RAISE
INCLINE_T_RAISE
INCLINE_W_RAISE
INCLINE_Y_RAISE
LYING_EXTERNAL_ROTATION
LYING_INTERNAL_ROTATION
SEATED_DUMBBELL_EXTERNAL_ROTATION
SEATED_DUMBBELL_INTERNAL_ROTATION
STANDING_L_RAISE
SWISS_BALL_I_RAISE
SWISS_BALL_T_RAISE
SWISS_BALL_W_RAISE
SWISS_BALL_Y_RAISE
WEIGHTED_FLOOR_I_RAISE
WEIGHTED_FLOOR_T_RAISE
WEIGHTED_FLOOR_Y_RAISE
WEIGHTED_INCLINE_I_RAISE
WEIGHTED_INCLINE_L_RAISE
WEIGHTED_INCLINE_T_RAISE
WEIGHTED_INCLINE_W_RAISE
WEIGHTED_INCLINE_Y_RAISE
WEIGHTED_SWISS_BALL_I_RAISE
WEIGHTED_SWISS_BALL_T_RAISE
WEIGHTED_SWISS_BALL_W_RAISE
WEIGHTED_SWISS_BALL_Y_RAISE
_90_DEGREE_CABLE_EXTERNAL_ROTATION
```

### SHRUG

**19 exercises**

```
BARBELL_JUMP_SHRUG
BARBELL_SHRUG
BARBELL_UPRIGHT_ROW
BEHIND_THE_BACK_SHRUG
BEHIND_THE_BACK_SMITH_MACHINE_SHRUG
DUMBBELL_JUMP_SHRUG
DUMBBELL_SHRUG
DUMBBELL_UPRIGHT_ROW
INCLINE_DUMBBELL_SHRUG
OVERHEAD_BARBELL_SHRUG
OVERHEAD_DUMBBELL_SHRUG
SCAPTION_AND_SHRUG
SCAPULAR_RETRACTION
SERRATUS_CHAIR_SHRUG
SERRATUS_SHRUG
WEIGHTED_SERRATUS_CHAIR_SHRUG
WEIGHTED_SERRATUS_SHRUG
WIDE_GRIP_BARBELL_SHRUG
WIDE_GRIP_JUMP_SHRUG
```

### SIT\_UP

**41 exercises**

```
ALTERNATING_SIT_UP
BENT_KNEE_V_UP
BUTTERFLY_SIT_UP
CROSSED_ARMS_SIT_UP
CROSS_PUNCH_ROLL_UP
GET_UP_SIT_UP
GHD_SIT_UPS
HOVERING_SIT_UP
KETTLEBELL_SIT_UP
MEDICINE_BALL_ALTERNATING_V_UP
MEDICINE_BALL_SIT_UP
MEDICINE_BALL_V_UP
MODIFIED_SIT_UP
NEGATIVE_SIT_UP
ONE_ARM_FULL_SIT_UP
RECLINING_CIRCLE
REVERSE_CURL_UP
RUSSIAN_TWIST_ON_SWISS_BALL
SINGLE_LEG_SWISS_BALL_JACKKNIFE
SIT_UP
SIT_UP_TURKISH_GET_UP
THE_TEASER
THE_TEASER_WEIGHTED
THREE_PART_ROLL_DOWN
V_UP
WEIGHTED_ALTERNATING_SIT_UP
WEIGHTED_BENT_KNEE_V_UP
WEIGHTED_BUTTERFLY_SITUP
WEIGHTED_CROSSED_ARMS_SIT_UP
WEIGHTED_CROSS_PUNCH_ROLL_UP
WEIGHTED_GET_UP_SIT_UP
WEIGHTED_HOVERING_SIT_UP
WEIGHTED_RECLINING_CIRCLE
WEIGHTED_REVERSE_CURL_UP
WEIGHTED_RUSSIAN_TWIST_ON_SWISS_BALL
WEIGHTED_SINGLE_LEG_SWISS_BALL_JACKKNIFE
WEIGHTED_SIT_UP
WEIGHTED_THREE_PART_ROLL_DOWN
WEIGHTED_V_UP
WEIGHTED_X_ABS
X_ABS
```

### SLED

**5 exercises**

```
BACKWARD_DRAG
CHEST_PRESS
FORWARD_DRAG
LOW_PUSH
PUSH
```

### SLEDGE\_HAMMER

**2 exercises**

```
HAMMER_SLAM
LATERAL_SWING
```

### SQUAT

**90 exercises**

```
AIR_SQUAT
BACK_SQUATS
BACK_SQUAT_WITH_BODY_BAR
BALANCING_SQUAT
BARBELL_BACK_SQUAT
BARBELL_BOX_SQUAT
BARBELL_FRONT_SQUAT
BARBELL_HACK_SQUAT
BARBELL_HANG_SQUAT_SNATCH
BARBELL_QUARTER_SQUAT
BARBELL_SIFF_SQUAT
BARBELL_SQUAT_SNATCH
BARBELL_SQUAT_WITH_HEELS_RAISED
BARBELL_STEPOVER
BENCH_SQUAT_WITH_ROTATIONAL_CHOP
BODY_WEIGHT_WALL_SQUAT
BOX_STEP_SQUAT
BRACED_SQUAT
CROSSED_ARM_BARBELL_FRONT_SQUAT
DUMBBELL_FRONT_SQUAT
DUMBBELL_OVERHEAD_SQUAT_SINGLE_ARM
DUMBBELL_SPLIT_SQUAT
DUMBBELL_SQUAT
DUMBBELL_SQUAT_CLEAN
DUMBBELL_SQUAT_SNATCH
DUMBBELL_STEPOVER
DUMBBELL_THRUSTERS
ELEVATED_SINGLE_LEG_SQUAT
FIGURE_FOUR_SQUATS
GOBLET_SQUAT
KETTLEBELL_SQUAT
KETTLEBELL_SWING_OVERHEAD
KETTLEBELL_SWING_WITH_FLIP_TO_SQUAT
LEG_PRESS
MEDICINE_BALL_SQUAT
ONE_LEGGED_SQUAT
OVERHEAD_BARBELL_SQUAT
OVERHEAD_DUMBBELL_SQUAT
OVERHEAD_SQUAT
PARTIAL_SINGLE_LEG_SQUAT
PILATES_PLIE_SQUATS_PARALLEL_TURNED_OUT_FLAT_AND_HEELS
PISTOL_SQUAT
PLIE_SLIDES
PLIE_SQUAT
PRISONER_SQUAT
RELEVE_STRAIGHT_LEG_AND_KNEE_BENT_WITH_ONE_LEG_VARIATION
SINGLE_LEG_BENCH_GET_UP
SINGLE_LEG_BENCH_SQUAT
SINGLE_LEG_SQUAT_ON_SWISS_BALL
SQUATS_WITH_BAND
SQUAT_AMERICAN_SWING
SQUAT_AND_SIDE_KICK
SQUAT_JUMPS_IN_N_OUT
STAGGERED_SQUAT
SUITCASE_SQUATS
SUMO_SQUAT
SUMO_SQUAT_SLIDE_IN
SUMO_SQUAT_TO_HIGH_PULL
SUMO_SQUAT_TO_STAND
SUMO_SQUAT_WITH_ROTATION
SWISS_BALL_BODY_WEIGHT_WALL_SQUAT
THRUSTERS
UNEVEN_SQUAT
WAIST_SLIMMING_SQUAT
WALL_BALL
WALL_BALL_SQUAT_AND_PRESS
WEIGHTED_BACK_SQUATS
WEIGHTED_BALANCING_SQUAT
WEIGHTED_BENCH_SQUAT_WITH_ROTATIONAL_CHOP
WEIGHTED_BOX_STEP_SQUAT
WEIGHTED_ELEVATED_SINGLE_LEG_SQUAT
WEIGHTED_FIGURE_FOUR_SQUATS
WEIGHTED_PARTIAL_SINGLE_LEG_SQUAT
WEIGHTED_PISTOL_SQUAT
WEIGHTED_PLIE_SLIDES
WEIGHTED_PLIE_SQUAT
WEIGHTED_PRISONER_SQUAT
WEIGHTED_SINGLE_LEG_BENCH_GET_UP
WEIGHTED_SINGLE_LEG_BENCH_SQUAT
WEIGHTED_SINGLE_LEG_SQUAT_ON_SWISS_BALL
WEIGHTED_SQUAT
WEIGHTED_STAGGERED_SQUAT
WEIGHTED_SUMO_SQUAT_SLIDE_IN
WEIGHTED_SUMO_SQUAT_TO_STAND
WEIGHTED_SUMO_SQUAT_WITH_ROTATION
WEIGHTED_SWISS_BALL_WALL_SQUAT
WEIGHTED_UNEVEN_SQUAT
WEIGHTED_WALL_SQUAT
WIDE_STANCE_BARBELL_SQUAT
WIDE_STANCE_GOBLET_SQUAT
```

### STAIR\_STEPPER

**9 exercises**

```
ALTERNATING_BOX_DUMBBELL_STEP_UPS
BARBELL_LATERAL_STEP_UP
BARBELL_STEP_UP
CROSSOVER_DUMBBELL_STEP_UP
DUMBBELL_STEP_UP
LATERAL_DUMBBELL_STEP_UP
STAIR_STEPPER
STEP_UP
WEIGHTED_STEP_UP
```

### SUSPENSION

**18 exercises**

```
CHEST_FLY
DIP
HAMSTRING_CURL
HIP_DROP
KNEE_DRIVE_JUMP
KNEE_TO_CHEST
LAT_PULLOVER
PENDULUM
PIKE
POWER_PULL
REVERSE_MOUNTAIN_CLIMBER
REVERSE_PLANK
ROLLOUT
SINGLE_LEG_DEADLIFT
SINGLE_LEG_SQUAT
SQUAT_JUMP
TRICEP_PRESS
Y_FLY
```

### TIRE

**1 exercises**

```
FLIP
```

### TOTAL\_BODY

**18 exercises**

```
BARBELL_BURPEE
BURPEE
BURPEE_BOX_JUMP
BURPEE_BOX_JUMP_OVER
BURPEE_BOX_JUMP_STEP_UP_OVER
HIGH_PULL_BURPEE
LATERAL_BARBELL_BURPEE
MAN_MAKERS
ONE_ARM_BURPEE
SQUAT_PLANK_PUSH_UP
SQUAT_THRUSTS
STANDING_T_ROTATION_BALANCE
TOTAL_BODY_BURPEE_OVER_BAR
WEIGHTED_BURPEE
WEIGHTED_BURPEE_BOX_JUMP
WEIGHTED_SQUAT_PLANK_PUSH_UP
WEIGHTED_SQUAT_THRUSTS
WEIGHTED_STANDING_T_ROTATION_BALANCE
```

### TRICEPS\_EXTENSION

**43 exercises**

```
ALTERNATING_DUMBBELL_LYING_TRICEPS_EXTENSION
BENCH_DIP
BODY_WEIGHT_DIP
CABLE_KICKBACK
CABLE_LYING_TRICEPS_EXTENSION
CABLE_OVERHEAD_TRICEPS_EXTENSION
DUMBBELL_KICKBACK
DUMBBELL_LYING_TRICEPS_EXTENSION
EZ_BAR_OVERHEAD_TRICEPS_EXTENSION
INCLINE_DIP
INCLINE_EZ_BAR_LYING_TRICEPS_EXTENSION
LYING_DUMBBELL_PULLOVER_TO_EXTENSION
LYING_EZ_BAR_TRICEPS_EXTENSION
LYING_TRICEPS_EXTENSION_TO_CLOSE_GRIP_BENCH_PRESS
OVERHEAD_DUMBBELL_TRICEPS_EXTENSION
RECLINING_TRICEPS_PRESS
REVERSE_GRIP_PRESSDOWN
REVERSE_GRIP_TRICEPS_PRESSDOWN
ROPE_PRESSDOWN
SEATED_BARBELL_OVERHEAD_TRICEPS_EXTENSION
SEATED_DUMBBELL_OVERHEAD_TRICEPS_EXTENSION
SEATED_EZ_BAR_OVERHEAD_TRICEPS_EXTENSION
SEATED_SINGLE_ARM_OVERHEAD_DUMBBELL_EXTENSION
SINGLE_ARM_DUMBBELL_OVERHEAD_TRICEPS_EXTENSION
SINGLE_DUMBBELL_SEATED_OVERHEAD_TRICEPS_EXTENSION
SINGLE_LEG_BENCH_DIP_AND_KICK
SINGLE_LEG_DIP
STATIC_LYING_TRICEPS_EXTENSION
SUSPENDED_DIP
SWISS_BALL_DUMBBELL_LYING_TRICEPS_EXTENSION
SWISS_BALL_EZ_BAR_LYING_TRICEPS_EXTENSION
SWISS_BALL_EZ_BAR_OVERHEAD_TRICEPS_EXTENSION
TABLETOP_DIP
TRICEPS_EXTENSION_ON_FLOOR
TRICEPS_PRESS
TRICEPS_PRESSDOWN
WEIGHTED_BENCH_DIP
WEIGHTED_DIP
WEIGHTED_INCLINE_DIP
WEIGHTED_SINGLE_LEG_BENCH_DIP_AND_KICK
WEIGHTED_SINGLE_LEG_DIP
WEIGHTED_SUSPENDED_DIP
WEIGHTED_TABLETOP_DIP
```

### WARM\_UP

**39 exercises**

```
NECK_ROTATIONS
STANDING_HAMSTRING_STRETCH
STRETCH_90_90
STRETCH_ABS
STRETCH_BUTTERFLY
STRETCH_CALF
STRETCH_CAT_COW
STRETCH_CHILDS_POSE
STRETCH_COBRA
STRETCH_FOREARMS
STRETCH_FORWARD_GLUTES
STRETCH_FRONT_SPLIT
STRETCH_HAMSTRING
STRETCH_HIP_FLEXOR_AND_QUAD
STRETCH_LAT
STRETCH_LEVATOR_SCAPULAE
STRETCH_LUNGE_WITH_SPINAL_TWIST
STRETCH_LUNGING_HIP_FLEXOR
STRETCH_LYING_ABDUCTION
STRETCH_LYING_IT_BAND
STRETCH_LYING_KNEE_TO_CHEST
STRETCH_LYING_PIRIFORMIS
STRETCH_LYING_SPINAL_TWIST
STRETCH_NECK
STRETCH_OBLIQUES
STRETCH_OVER_UNDER_SHOULDER
STRETCH_PECTORAL
STRETCH_PIGEON_POSE
STRETCH_PIRIFORMIS
STRETCH_QUAD
STRETCH_SCORPION
STRETCH_SHOULDER
STRETCH_SIDE
STRETCH_SIDE_LUNGE
STRETCH_SIDE_SPLIT
STRETCH_STANDING_IT_BAND
STRETCH_STRADDLE
STRETCH_TRICEPS
STRETCH_WALL_CHEST_AND_SHOULDER
```

***

### Summary

* **Total exercises:** 1624
* **Total categories:** 49


# Overview

Push GPS routes to your users' Garmin, COROS, Wahoo and Hammerhead devices.

The Routes API pushes GPS courses to your users' fitness devices, so they don't have to recreate them by hand on their watch or bike computer. Your app can:

* **Create reusable route templates**: define the route once, with its waypoints.
* **Push to any user**: send the route to a user's connected device.
* **Keep devices up to date**: an update to the template reaches every user it was pushed to.

Routes work with Garmin, COROS, Wahoo and Hammerhead. Not every provider supports every operation; see [Provider compatibility](/routes-api/provider-compatibility).

Routes are part of the [Planned Workouts add-on](/planned-workouts-api/pricing). Each push, and each pushed route an update re-sends, costs 10 Planned Workouts credits, like a workout push. Reads and deletes are free. Without the add-on, every Routes endpoint except the deletes returns `403 Forbidden`.

## How it works

You create a route template once, then push it to each user.

```
┌─────────────────────────────────────────────────────────────────┐
│  Phase 1: Create Template (once)                                │
│  POST /routes                                                   │
│  → Returns route_id                                             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│  Phase 2: Push to User                                          │
│  POST /routes/{route_id}/push?user_id=X                         │
│  → Sends the route to the user's provider                       │
│  → Appears on the user's device after its next sync             │
└─────────────────────────────────────────────────────────────────┘
```

## Authentication

Every request needs two headers:

| Header      | Description       |
| ----------- | ----------------- |
| `dev-id`    | Your developer ID |
| `x-api-key` | Your API key      |

## Quickstart

### Create a route template

Create a simple running loop:

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "Morning Run Loop",
    "sport": "running",
    "waypoints": [
      { "latitude": 51.5074, "longitude": -0.1278, "elevation_meters": 10 },
      { "latitude": 51.5120, "longitude": -0.1220, "elevation_meters": 30 },
      { "latitude": 51.5160, "longitude": -0.1180, "elevation_meters": 55 },
      { "latitude": 51.5120, "longitude": -0.1140, "elevation_meters": 70 },
      { "latitude": 51.5074, "longitude": -0.1278, "elevation_meters": 10 }
    ]
  }'
```

Response (`200 OK`):

```json
{
  "status": "success",
  "route_id": "295581149349019648"
}
```

Distance comes from the waypoints, and elevation gain and loss are worked out from them when every waypoint has `elevation_meters`.

### Push it to a user

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes/295581149349019648/push?user_id=USER_ID" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY"
```

Response (`201 Created`):

```json
{
  "status": "success",
  "pushed_route_id": "295581443239706624",
  "provider_route_id": "1774538415035"
}
```

The route appears on the user's device after its next sync. Keep `pushed_route_id`: it is Terra's ID for this user's copy of the route.

Pushing the same route to the same user again re-sends their pushed route instead of adding a second one. It returns `200 OK` with the same `pushed_route_id`.

## API endpoints

| Method | Endpoint                                    | Description                                                     |
| ------ | ------------------------------------------- | --------------------------------------------------------------- |
| POST   | `/routes`                                   | Create a route template                                         |
| GET    | `/routes`                                   | List your route templates                                       |
| PUT    | `/routes/{route_id}`                        | Update a template and re-send it to every user it was pushed to |
| DELETE | `/routes/{route_id}`                        | Remove the route from every user's device, then delete it       |
| POST   | `/routes/{route_id}/push?user_id=X`         | Push a route to a user's device                                 |
| GET    | `/pushedRoutes?user_id=X`                   | List the routes pushed to a user                                |
| GET    | `/pushedRoutes/{pushed_route_id}?user_id=X` | Get one pushed route                                            |
| DELETE | `/pushedRoutes/{pushed_route_id}?user_id=X` | Remove a route from one user's device                           |

`user_id` is the Terra user ID of one provider connection, as for the rest of the API.

## Next steps

* [Core concepts](/routes-api/core-concepts): route templates, waypoints, pushed routes, updates, deletes, errors and validation
* [Sport-specific examples](/routes-api/sport-specific-examples): copy-paste routes for running, trail running, hiking and cycling
* [Provider compatibility](/routes-api/provider-compatibility): what Garmin, COROS, Wahoo and Hammerhead support


# Core concepts

Route templates, waypoints, pushed routes, updates, deletes and errors.

### Route templates

A route template is a named sequence of GPS waypoints. You create it once and push it to as many users as you like.

| Field                     | Required | Description                                                             |
| ------------------------- | -------- | ----------------------------------------------------------------------- |
| `name`                    | Yes      | Route name shown on the device, up to 255 characters                    |
| `sport`                   | Yes      | Sport type, lowercase (see [Sport types](#sport-types))                 |
| `waypoints`               | Yes      | 2 to 10,000 GPS points, in order                                        |
| `description`             | No       | Up to 2,000 characters. Garmin shows it; other providers ignore it.     |
| `elevation_gain_meters`   | No       | Total elevation gain in meters, 0 or more                               |
| `elevation_loss_meters`   | No       | Total elevation loss in meters, 0 or more                               |
| `speed_meters_per_second` | No       | Average speed of the course, above 0. Garmin uses it; others ignore it. |

If you leave out `elevation_gain_meters` and `elevation_loss_meters`, Terra works them out from the waypoints when every waypoint has `elevation_meters`. Otherwise they are 0.

{% hint style="warning" %}
Fields the API doesn't recognize are ignored without an error. Check field names against these tables: a misspelled field is dropped silently.
{% endhint %}

### Waypoints

| Field              | Required | Description                                        |
| ------------------ | -------- | -------------------------------------------------- |
| `latitude`         | Yes      | Decimal degrees, -90 to 90                         |
| `longitude`        | Yes      | Decimal degrees, -180 to 180                       |
| `elevation_meters` | No       | Meters above sea level, -500 to 9,000              |
| `course_point`     | No       | A point of interest at this waypoint. Garmin only. |

### Course points

A course point marks a point of interest on the route, such as a water stop:

```json
{
  "latitude": 51.5120,
  "longitude": -0.1220,
  "course_point": {
    "type": "water",
    "name": "Water Station"
  }
}
```

`type` is one of `generic`, `summit`, `valley`, `water`, `food`, `danger`, `first_aid`, `sprint`, `segment_start`, `segment_end`, `left`, `right`, `straight`, `left_fork` and `right_fork`. Any other value returns `400 Bad Request`.

Only Garmin shows course points, and it doesn't show `left`, `right`, `straight`, `left_fork` or `right_fork`. Other providers ignore course points; the rest of the route still arrives.

### Sport types

`running`, `trail_running`, `hiking`, `cycling`, `road_biking`, `mountain_biking`, `gravel_cycling` and `other`. Every provider accepts every sport. COROS groups them into running (`running`, `trail_running`, `hiking`) and cycling (everything else).

### Pushed routes

A pushed route is one user's copy of a route on their device. `POST /routes/{route_id}/push?user_id=X` creates it and returns two IDs:

* `pushed_route_id`: Terra's ID for this user's copy. Use it with the `/pushedRoutes` endpoints.
* `provider_route_id`: the ID the provider gave the route. It can change: Garmin, Wahoo and Hammerhead recreate a route the user deleted from their device under a new ID, and Hammerhead also replaces a route whose update keeps the same path (see [Provider compatibility](/routes-api/provider-compatibility#hammerhead)).

Pushing the same route to the same user again re-sends their pushed route instead of creating a second one. The first push returns `201 Created`; a repeat returns `200 OK` with the same `pushed_route_id`. Both cost 10 Planned Workouts credits; a push the provider rejects is free.

To find a user's pushed routes later, call `GET /pushedRoutes?user_id=X`. Each item has `pushed_route_id`, `route_id`, `provider_route_id`, `created_at` and `last_updated_at`.

### Update a route

```
PUT /routes/{route_id}
```

Send only the fields you want to change. `waypoints`, if you send it, replaces the whole list. The same validation applies as on create.

Every update is re-sent to every user the route was pushed to, and each pushed route that comes back `updated` costs 10 Planned Workouts credits. The response lists each pushed route:

```json
{
  "status": "success",
  "route_id": "295581149349019648",
  "pushed_routes": [
    {
      "pushed_route_id": "295581443239706624",
      "provider_route_id": "1774538415035",
      "status": "updated"
    }
  ]
}
```

| Status    | Meaning                                                                                                                                                  |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `updated` | The provider has the new version.                                                                                                                        |
| `failed`  | The provider did not take it, and `error` has its reason. Repeat the request to re-send.                                                                 |
| `skipped` | Terra can no longer reach this user's device, for example because they disconnected or their provider authorization lapsed. The user needs to reconnect. |

If any pushed route failed, the response is `207 Multi-Status`, with a `message` in place of `status`:

```json
{
  "message": "1 of 2 pushed copies were not updated; the route itself is saved, so repeat the request to re-send them",
  "route_id": "295581149349019648",
  "pushed_routes": [
    { "pushed_route_id": "295581443239706624", "provider_route_id": "1774538415035", "status": "updated" },
    { "pushed_route_id": "295581443239706625", "provider_route_id": "117280.route.3f1c", "status": "failed", "error": "unprocessable request: hammerhead rejected route update (status 400)" }
  ]
}
```

The template is already saved, so repeating the same `PUT` re-sends it.

{% hint style="info" %}
An update can re-send to at most 50 pushed routes. For a route pushed to more users, `PUT` returns `422 Unprocessable Entity` and nothing changes. Create a new route instead.
{% endhint %}

### Delete routes

`DELETE /routes/{route_id}` removes the route from every user's device, then deletes the template, and returns `204 No Content`.

* If a provider refuses to delete a pushed route, the response is `207 Multi-Status` with each pushed route's `status` (`deleted`, `failed` or `skipped`). The template and the pushed routes that failed are kept, so repeat the request to finish.
* A `skipped` pushed route can't be reached (the user disconnected) and doesn't block the delete: it may stay on that user's device.

`DELETE /pushedRoutes/{pushed_route_id}?user_id=X` removes a route from one user's device. It always returns `204 No Content` and removes the pushed route from Terra, even if the provider could not delete its copy.

On COROS, deletes remove the route from Terra only. It stays on the device.

### Concurrent requests

Pushes, updates and deletes of the same route run one at a time. A request that arrives while another is still running on that route returns `409 Conflict`. Retry it after a short wait.

### Errors

Errors use the standard problem format: `type`, `title`, `detail` and `instance`, plus `errors` for validation failures.

| Status   | When                                                                                            | What to do                                       |
| -------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| 400      | The request failed validation. `errors` lists why.                                              | Fix the request.                                 |
| 403      | Your account doesn't have the Planned Workouts add-on, or the user hasn't allowed route access. | Enable the add-on, or ask the user to reconnect. |
| 404      | The route or pushed route doesn't exist, or the user's provider doesn't support routes.         | Check the IDs and the provider.                  |
| 409      | Another request is changing the same route.                                                     | Retry after a short wait.                        |
| 422      | An update would re-send to more than 50 pushed routes.                                          | Create a new route instead.                      |
| 424      | The provider rejected a push. `detail` has its reason.                                          | Fix the route, or check the provider's limits.   |
| 429      | The provider rate-limited the request.                                                          | Retry later.                                     |
| 503, 504 | The provider is unavailable or timed out.                                                       | Retry later.                                     |

### Complete example

A 5 km running loop with elevation and a water stop:

```json
{
  "name": "Morning Run Loop",
  "sport": "running",
  "description": "5 km loop with slight elevation",
  "waypoints": [
    { "latitude": 51.5074, "longitude": -0.1278, "elevation_meters": 10 },
    {
      "latitude": 51.5120,
      "longitude": -0.1220,
      "elevation_meters": 30,
      "course_point": { "type": "water", "name": "Water Station" }
    },
    { "latitude": 51.5160, "longitude": -0.1180, "elevation_meters": 55 },
    { "latitude": 51.5120, "longitude": -0.1140, "elevation_meters": 70 },
    { "latitude": 51.5074, "longitude": -0.1278, "elevation_meters": 10 }
  ]
}
```


# Sport-specific examples

Copy-paste route templates for running, trail running, hiking and cycling.

Complete, copy-paste examples for each sport type. Each one creates a template; push it with `POST /routes/{route_id}/push?user_id=USER_ID`.

### Running

#### City loop with elevation

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "London 5K Loop",
    "sport": "running",
    "elevation_gain_meters": 45,
    "elevation_loss_meters": 45,
    "waypoints": [
      { "latitude": 51.5074, "longitude": -0.1278, "elevation_meters": 12 },
      { "latitude": 51.5100, "longitude": -0.1240, "elevation_meters": 20 },
      { "latitude": 51.5130, "longitude": -0.1200, "elevation_meters": 35 },
      { "latitude": 51.5150, "longitude": -0.1160, "elevation_meters": 50 },
      { "latitude": 51.5120, "longitude": -0.1130, "elevation_meters": 42 },
      { "latitude": 51.5090, "longitude": -0.1160, "elevation_meters": 28 },
      { "latitude": 51.5074, "longitude": -0.1278, "elevation_meters": 12 }
    ]
  }'
```

### Trail running

#### Mountain trail with course points

Only Garmin shows course points. Other providers receive the route without them.

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "Alpine Trail Loop",
    "sport": "trail_running",
    "elevation_gain_meters": 650,
    "elevation_loss_meters": 650,
    "waypoints": [
      { "latitude": 46.0000, "longitude": 7.0000, "elevation_meters": 1200 },
      { "latitude": 46.0100, "longitude": 7.0100, "elevation_meters": 1350 },
      {
        "latitude": 46.0200,
        "longitude": 7.0200,
        "elevation_meters": 1600,
        "course_point": { "type": "summit", "name": "Col du Sommet" }
      },
      { "latitude": 46.0300, "longitude": 7.0300, "elevation_meters": 1500 },
      {
        "latitude": 46.0350,
        "longitude": 7.0350,
        "elevation_meters": 1400,
        "course_point": { "type": "water", "name": "Stream Crossing" }
      },
      { "latitude": 46.0300, "longitude": 7.0400, "elevation_meters": 1300 },
      { "latitude": 46.0000, "longitude": 7.0000, "elevation_meters": 1200 }
    ]
  }'
```

### Hiking

#### Day hike with food and water stops

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "Peak District Day Hike",
    "sport": "hiking",
    "elevation_gain_meters": 480,
    "elevation_loss_meters": 480,
    "waypoints": [
      { "latitude": 53.3700, "longitude": -1.8300, "elevation_meters": 280 },
      { "latitude": 53.3780, "longitude": -1.8200, "elevation_meters": 380 },
      {
        "latitude": 53.3850,
        "longitude": -1.8100,
        "elevation_meters": 450,
        "course_point": { "type": "food", "name": "Lunch Spot" }
      },
      {
        "latitude": 53.3920,
        "longitude": -1.8000,
        "elevation_meters": 510,
        "course_point": { "type": "summit", "name": "Kinder Scout" }
      },
      { "latitude": 53.3870, "longitude": -1.7900, "elevation_meters": 430 },
      {
        "latitude": 53.3800,
        "longitude": -1.8000,
        "elevation_meters": 350,
        "course_point": { "type": "water", "name": "Edale Stream" }
      },
      { "latitude": 53.3700, "longitude": -1.8300, "elevation_meters": 280 }
    ]
  }'
```

### Road biking

#### Sportive route with speed target

Only Garmin uses `speed_meters_per_second`. Other providers ignore it.

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "Surrey Hills 80K",
    "sport": "road_biking",
    "elevation_gain_meters": 1200,
    "elevation_loss_meters": 1200,
    "speed_meters_per_second": 9.0,
    "waypoints": [
      { "latitude": 51.2300, "longitude": -0.3500, "elevation_meters": 50 },
      { "latitude": 51.2200, "longitude": -0.3200, "elevation_meters": 120 },
      {
        "latitude": 51.2100,
        "longitude": -0.2900,
        "elevation_meters": 220,
        "course_point": { "type": "danger", "name": "Sharp Descent" }
      },
      { "latitude": 51.2000, "longitude": -0.2600, "elevation_meters": 180 },
      {
        "latitude": 51.1900,
        "longitude": -0.2800,
        "elevation_meters": 250,
        "course_point": { "type": "summit", "name": "Box Hill" }
      },
      { "latitude": 51.2100, "longitude": -0.3100, "elevation_meters": 130 },
      { "latitude": 51.2300, "longitude": -0.3500, "elevation_meters": 50 }
    ]
  }'
```

### Minimal route (2 waypoints)

Smallest valid route.

```bash
curl -X POST "https://access.tryterra.co/api/v2/routes" \
  -H "Content-Type: application/json" \
  -H "dev-id: YOUR_DEV_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "name": "Quick Out-and-Back",
    "sport": "running",
    "waypoints": [
      { "latitude": 51.5074, "longitude": -0.1278 },
      { "latitude": 51.5150, "longitude": -0.1200 }
    ]
  }'
```


# Provider compatibility

What Garmin, COROS, Wahoo and Hammerhead support for routes.

Not every provider supports every route feature. This page shows what works where.

### Operations

|                        | Garmin | COROS | Wahoo | Hammerhead |
| ---------------------- | ------ | ----- | ----- | ---------- |
| **Push**               | ✓      | ✓     | ✓     | ✓          |
| **Update**             | ✓      | ✓\*   | ✓     | ✓          |
| **Delete from device** | ✓      | —†    | ✓     | ✓          |

\*COROS has no update API. Terra uploads the route again under the same route ID, and `provider_route_id` stays the same.

†COROS has no delete API. Deleting removes the route from Terra only, and it stays on the user's device. The API still returns success.

### Sports

Every provider accepts every sport. COROS groups them into running (`running`, `trail_running`, `hiking`) and cycling (everything else), so its devices may not tell a road ride from a gravel ride.

### Features

|                        | Garmin | COROS | Wahoo | Hammerhead |
| ---------------------- | ------ | ----- | ----- | ---------- |
| Elevation per waypoint | ✓‡     | ✓     | ✓     | ✓          |
| Elevation gain/loss    | ✓      | ✓     | ✓     | ✓          |
| Speed target           | ✓      | —     | —     | —          |
| Course points (POIs)   | ✓      | —     | —     | —          |
| Description            | ✓      | —     | —     | —          |

‡Garmin needs elevation on all waypoints or none. If only some waypoints have it, Terra drops all of it and Garmin fills elevation from its own model.

A provider that doesn't support a feature ignores it, and the rest of the route still arrives.

### Provider details

#### Garmin

**Limitations:**

* Doesn't show the `left`, `right`, `straight`, `left_fork` and `right_fork` course point types.
* Elevation must be on all waypoints or none.

**Behavior:**

* If the user deleted the course from their device, an update recreates it under a new `provider_route_id`.

***

#### COROS

**Limitations:**

* No update or delete API (see [Operations](#operations)).
* No course points, speed target or description.

***

#### Wahoo

**Limitations:**

* No course points, speed target or description.

**Behavior:**

* If the user deleted the route from their device, an update recreates it under a new `provider_route_id`.

***

#### Hammerhead

Routes go to the user's Karoo.

**Limitations:**

* No course points, speed target or description.
* The user must have allowed route access. Users who connected before route support was added need to reconnect; until they do, a push returns `403 Forbidden`.

**Behavior:**

* Hammerhead only updates a route in place when its path changes. If an update keeps the same waypoint positions, for example a new name or new elevations, Terra replaces the route on the device with a new one, under a new `provider_route_id`. A repeat push of an unchanged route does the same.
* If the user deleted the route from their device, an update recreates it under a new `provider_route_id`.

### Best practices

* Design for Garmin first: it supports the most features.
* Don't rely on course points unless your users are on Garmin.
* Put elevation on every waypoint or none.


# Overview

{% hint style="info" %}
The Terra Streaming API delivers real-time metrics on a roughly per-second basis:

* Heart rate
* Steps
* Distance covered
* and more, listed in [Data types](/streaming-api/data-types)

For longer-span data such as **workouts, sleep, daily totals & more**, use the [Unified API](/unified-api/getting-started) instead.
{% endhint %}

The Streaming API is a **paid add-on** to your Terra plan. See [Pricing](/streaming-api/pricing) for the $99/month add-on and how credits are measured.

The **Streaming API** gives access to wearables that broadcast over BLE (Bluetooth Low Energy), ANT+, or certain custom Bluetooth protocols, as well as phone sensors:

* Heart rate straps (Polar H10, Garmin HRM Pro, Wahoo TICKR FIT...)
* Certain smartwatches (Apple Watch, [Garmin Fenix 6 & up](https://support.garmin.com/en-US/?faq=Zj1947s6pqAHzBCAhLhrC9), Xiaomi Mi Band 5 & 6...)
* and more

<div data-full-width="true"><figure><img src="https://files.readme.io/51e8eaf-image.png" alt="" width="563"><figcaption><p>Data flow diagram for data streaming</p></figcaption></figure></div>

***

## How it works

Real-time streaming has **four parts**:

1. **Wearable device**: the heart-rate strap, watch, or sensor, broadcasting over BLE or ANT+.
2. **Producer**: your mobile app, running a Terra Real-Time (RT) SDK, which receives the wearable's data and forwards it to Terra.
3. **Terra WebSocket broker**: Terra's server, which routes the live stream. This is Terra's infrastructure; you don't run it.
4. **Consumer**: your backend, which connects to Terra and receives the stream.

You set up the **three connections** between them:

1. **Wearable → app:** the user pairs their wearable to your app over Bluetooth/ANT+ using a Terra RT SDK.
2. **App → Terra:** your app opens a *producer* connection to Terra's WebSocket and forwards the wearable's data.
3. **Terra → backend:** your backend opens a *consumer* connection to Terra's WebSocket and receives the data in real time.

***

## Before you begin

* **Get your credentials.** Grab your **Dev ID** and **API key** from the [Terra dashboard](https://dashboard.tryterra.co). Your backend uses these to generate the short-lived tokens each WebSocket connection needs: a *producer* token for your app and a *developer* token for your consumer.
* **Know your user IDs.** When your app connects a user with the RT SDK, you identify them by your own `reference_id`. Terra creates a Terra `user_id` for that user (no separate auth widget needed). That `user_id` is what your token endpoints take and what you'll see as the `uid` field on every streamed payload.

***

## Test without a wearable

You don't need physical hardware to build and verify your integration. From the **Streaming** page of the [Terra dashboard](https://dashboard.tryterra.co/dashboard/streaming), create a **test user** and Terra streams synthetic data (heart rate, steps, and more) through the live API, so you can stand up and validate your backend consumer end to end before connecting a real device.

***

## Next steps

1. Open the SDK page for your platform: [iOS](/streaming-api/ios-swift), [Android](/streaming-api/android), [React Native](/streaming-api/react-native), or [Flutter](/streaming-api/flutter). Each page covers the first two connections: connect a wearable to your app, then stream its data to Terra.
2. Set up a [backend consumer](/streaming-api/terra-greater-than-your-backend) to receive the live stream.

Only building the backend consumer (for example, you already have a producer, or you're testing with a synthetic test user)? Start with [Backend consumer](/streaming-api/terra-greater-than-your-backend), which documents the full WebSocket protocol: opcodes, payload shapes, and close codes.

{% hint style="success" %}
**Prefer to read working code?** [**Terra Grip**](https://docs.tryterra.co/developer-tools/example-apps/terra-grip) is a React Native reference app that implements the producer path end to end with the `terra-rt` SDK, covering pairing, tokens, and live streaming. [**Terra Pulse**](https://docs.tryterra.co/developer-tools/example-apps/terra-pulse) implements the consumer path: a React web app that opens a WebSocket to Terra and renders the stream live. Clone either, run it, and copy the parts you need.
{% endhint %}

{% hint style="info" %}
**Building with an AI coding assistant?** The `terra-streaming` [agent skill](https://docs.tryterra.co/developer-tools/agent-skills) gives your assistant the streaming architecture, the websocket protocol, and the platform gotchas up front, so it writes against the real contract instead of guessing.

```bash
npx skills add tryterra/agent-skills --skill terra-streaming
```

{% endhint %}


# Pricing

The Streaming API is a paid add-on, with usage measured in Streaming credits.

## The add-on

The Streaming API is available for **$99/month**, on its own or alongside any Terra plan. Activate it from the dashboard, either on the Streaming page itself or under **Settings → Plans & Pricing → Additional Products**.

Without the add-on active, all streaming authentication endpoints return `403 Forbidden`. No producer, consumer, or test-user tokens can be minted, so streaming (including the synthetic-data test mode) requires the add-on.

## Credits

Usage is measured in **Streaming credits**, a separate balance from your Unified API credits. Your subscription includes **20,000 Streaming credits per month**. Beyond that, they are billed at **$0.005 each** at the end of each billing cycle, and **$0.003 each** past 1,000,000 in a month. Included Streaming credits reset each billing cycle and do not roll over. Overage is billed, never blocked: streams are not cut off mid-session.

| Usage                                                                                  | Streaming credits                  |
| -------------------------------------------------------------------------------------- | ---------------------------------- |
| **Active streaming user**: a user who streams at least one event in the billing period | 1,000 credits ($5)                 |
| **Included events**: each active user's first 16,000 streamed events in the period     | Free                               |
| **Additional events**: each streamed event beyond a user's included 16,000             | 1/16 credit (16 events = 1 credit) |
| Synthetic test users (dashboard test mode)                                             | Free                               |

The included 20,000 Streaming credits cover **20 active streaming users per month** (each within their included events), or any mix of users and event overage.

{% hint style="info" %}
An **event** is one real-time payload streamed from a user's device, typically about one per second per active stream. It counts once, however many consumer connections receive it. The event allowance is applied per user: one heavy user cannot consume another user's unused headroom. Fractional Streaming credits round down in your favour, and duplicates are removed before counting.
{% endhint %}

### What this looks like in practice

* At roughly one event per second, a user's included 16,000 events cover about **4.5 hours of live streaming per month**.
* Each additional hour of continuous per-second streaming is about 225 Streaming credits (**≈ $1.13/hour**).
* A team of 20 users doing weekly one-hour live sessions (≈ 4 hours each/month) fits entirely inside the included 20,000 Streaming credits: **$99/month total**.

## Access states

* **Add-on active**: full access, including producer, consumer and SDK token minting, live streaming, replay and test mode.
* **Add-on not active**: token minting returns `403 Forbidden`. Existing sessions end when their tokens expire; nothing else about your Terra plan is affected.


# Supported devices

The wearables the RT SDKs can stream from, grouped by brand.

Real-time streaming works with wearables that broadcast heart rate data over BLE. The devices below are the ones we support, grouped by brand.

| Brand       | Supported models                                                                                                                                              |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Apple Watch | Series 1 to 11, SE (1st to 3rd generation), Ultra (1st to 3rd generation)                                                                                     |
| Garmin      | HRM-Dual, HRM-Pro, HRM-Pro Plus, and every Garmin watch that supports [heart rate broadcasting](https://support.garmin.com/en-US/?faq=Zj1947s6pqAHzBCAhLhrC9) |
| MyZone      | Go, HRM MZ, HRM MZ-2, HRM MZ-3                                                                                                                                |
| Polar       | H9, H10, OH1, Verity Sense                                                                                                                                    |
| Samsung     | Galaxy Watch4 to Watch8, Watch FE, Watch Ultra                                                                                                                |
| Suunto      | Smart Heart Rate Belt                                                                                                                                         |
| Ultrahuman  | Ring AIR                                                                                                                                                      |
| Wahoo       | TICKR, TICKR 2, TICKR FIT, TICKR X, TICKR X2                                                                                                                  |
| Wear OS     | Watches running Wear OS 7 and later                                                                                                                           |
| WHOOP       | 4.0, 5.0                                                                                                                                                      |
| Xiaomi      | Bands, 5th to 10th generation                                                                                                                                 |

Bryton and Hammerhead devices are also supported.


# iOS SDK

Connect a BLE wearable or Apple Watch to your iOS app with TerraRTiOS, then stream its data to Terra.

## Install the SDK

{% hint style="danger" %}
**RealTime streaming on iOS is only available to those registered on the** [**Apple Developer Program**](https://developer.apple.com/programs/enroll/)
{% endhint %}

{% embed url="<https://app.arcade.software/share/FYXtrn9eKX2WqnmrTmNU>" %}

1. Add <https://github.com/tryterra/TerraRTiOS> as a package dependency
2. In your info.plist, add:
   1. `Privacy - Bluetooth Always Usage Description`: Justification for BLE usage (shown to the user when requesting permission)
   2. `Privacy - Motion Usage Description`: Justification for phone motion sensor usage (shown to the user when requesting permission, only add if using phone sensors for streaming)

When the app is launched for the first time, these permissions will be requested from the user.

***

## Set up the connection

The SDK revolves around the `TerraRT` class, which manages Bluetooth connections and real-time data streaming.

### Initialize the SDK

{% hint style="info" %}
Always initialize the `TerraRT` class to begin using the SDK.

Do so every time the app is opened or brought into the foreground.
{% endhint %}

```swift
import TerraRTiOS

let developerId = "yourDeveloperId"
let referenceId: String? = "yourReferenceId"

let terraRT = TerraRT(devId: developerId, referenceId: referenceId) { success in
    if success {
        print("TerraRT initialization successful!")
    } else {
        print("TerraRT initialization failed.")
    }
}
```

### Register the phone

Register the [phone](https://docs.tryterra.co/introduction/core-concepts#streaming-api) by calling [`initConnection`](https://docs.tryterra.co/reference/streaming-api/ios-swift#initconnection).

This connects the [phone](https://docs.tryterra.co/introduction/core-concepts#streaming-api) to Terra, allows you to use other SDK functions, and allows it to be a [producer](https://docs.tryterra.co/introduction/core-concepts#streaming-api) once a [wearable](https://docs.tryterra.co/introduction/core-concepts#streaming-api) is connected later on.

```swift
let token = "yourAuthToken"  // Generated from your backend

terraRT.initConnection(token: token) { success in
    if success {
        print("Connection initialized successfully!")
    } else {
        print("Failed to initialize connection.")
    }
}
```

To generate the **token**, make the below call **from your backend**

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>" path="/auth/generateAuthToken" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>
{% endopenapi %}

### Connect a device

iOS devices support connection via BLE or Apple Watch's WatchConnectivity protocol. For Apple Watch, see [Stream from an Apple Watch](#stream-from-an-apple-watch).

The [`startBluetoothScan`](https://docs.tryterra.co/reference/streaming-api/ios-swift#startbluetoothscan-with-built-in-ui) function returns a SwiftUI `TerraBLEWidget` view for device selection:

```swift
import SwiftUI
import TerraRTiOS

struct BluetoothScanView: View {
    @State private var scanWidget: TerraBLEWidget?
    @State private var connected = false

    var body: some View {
        VStack {
            if let widget = scanWidget {
                widget
            }

            if connected {
                Text("Device connected!")
                    .foregroundColor(.green)
            }

            Button("Start Bluetooth Scan") {
                scanWidget = terraRT.startBluetoothScan(type: .BLE) { success in
                    connected = success
                }
            }
        }
        .padding()
    }
}
```

***

## Stream data to your app

Once the [phone is registered](#register-the-phone) and you've [connected a wearable](#connect-a-device), you can stream data from the wearable to your mobile app.

### Start streaming

Call [`startRealtime`](https://docs.tryterra.co/reference/streaming-api/ios-swift#startrealtime-local-only) to stream data to your app locally (without sending to Terra's server):

```swift
import TerraRTiOS

let connectionType: Connections = .BLE
let dataTypes: Set<DataTypes> = [.HEART_RATE, .STEPS]

terraRT.startRealtime(type: connectionType, dataType: dataTypes) { update in
    if let value = update.val {
        print("\(update.type ?? ""): \(value)")
    }
    if let dataArray = update.d {
        print("\(update.type ?? ""): \(dataArray)")
    }
}
```

To also send data to Terra's server, see [Stream to Terra](#stream-to-terra).

### Stop streaming and disconnect

```swift
terraRT.stopRealtime(type: .BLE)
terraRT.disconnect(type: .BLE)
```

***

## Stream from an Apple Watch

{% hint style="info" %}
To receive a data stream from an Apple Watch, the watch must be instructed to initiate a data stream to the iOS [phone](https://docs.tryterra.co/introduction/core-concepts#streaming-api) it is paired with.

For that, you'll need to have a WatchOS companion app running on the watch, which runs [`startStream`](https://docs.tryterra.co/reference/streaming-api/ios-swift#startstream) or [`startExercise`](https://docs.tryterra.co/reference/streaming-api/ios-swift#startexercise)
{% endhint %}

### Add a watchOS target

1. Create a WatchOS target within your iOS project:

   File > New > Target > Watch App for iOS App.
2. Enable **HealthKit** and **Background Modes** for the WatchOS app, and add the following privacy keys to your `Info.plist`:
   1. `Privacy - Health Share Usage Description`
   2. `Privacy - Health Update Usage Description`
   3. `Privacy - Health Records Usage Description`

### Start streaming from the watch

{% hint style="info" %}
Outside of a workout session, data recording frequency may be reduced. In order to capture data at the highest possible frequency, you'll want to [start a workout session](#stream-workouts-from-the-watch)
{% endhint %}

On the iOS app, listen for updates from the WatchOS app using `startRealtime` with `.WATCH_OS`:

{% tabs %}
{% tab title="WatchOS app" %}

```swift
import WatchKit
import TerraRTiOS

class InterfaceController: WKInterfaceController {
    var terra: Terra?

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        do {
            terra = try Terra()
            terra?.connect()
            print("Terra SDK initialized on watchOS")
            startStreamingData()
        } catch {
            print("Failed to initialize Terra SDK: \(error)")
        }
    }

    func startStreamingData() {
        let dataTypes: Set<ReadTypes> = [.HEART_RATE, .STEPS]
        terra?.startStream(forDataTypes: dataTypes) { success, error in
            if success {
                print("Streaming started")
            } else {
                print("Failed: \(error?.localizedDescription ?? "Unknown error")")
            }
        }
    }

    func stopStreamingData() {
        terra?.stopStream()
    }
}
```

{% endtab %}

{% tab title="iOS app" %}

```swift
import TerraRTiOS
import UIKit

class ViewController: UIViewController {
    var terraRT: TerraRT?

    override func viewDidLoad() {
        super.viewDidLoad()

        terraRT = TerraRT(devId: "your-dev-id", referenceId: "your-reference-id") { success in
            if success {
                print("Terra SDK initialized")
                self.setupWatchOSConnection()
            }
        }
    }

    func setupWatchOSConnection() {
        try? terraRT?.connectWithWatchOS()
        listenForDataFromWatch()
    }

    func listenForDataFromWatch() {
        let dataTypes: Set<DataTypes> = [.HEART_RATE, .STEPS]
        terraRT?.startRealtime(type: .WATCH_OS, dataType: dataTypes) { update in
            print("Watch update: \(update.type ?? ""): \(update.val ?? 0)")
        }
    }

    func stopRealtimeData() {
        terraRT?.stopRealtime(type: .WATCH_OS)
    }

    func disconnectWatchOS() {
        terraRT?.disconnect(type: .WATCH_OS)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        stopRealtimeData()
        disconnectWatchOS()
    }
}
```

{% endtab %}
{% endtabs %}

### Stream workouts from the watch

The Apple Watch app can also manage a workout session, during which recording frequency is enhanced.

From the Watch: [`startExercise`](https://docs.tryterra.co/reference/streaming-api/ios-swift#startexercise), [`stopExercise`](https://docs.tryterra.co/reference/streaming-api/ios-swift#stopexercise), [`pauseExercise`](https://docs.tryterra.co/reference/streaming-api/ios-swift#pauseexercise), [`resumeExercise`](https://docs.tryterra.co/reference/streaming-api/ios-swift#resumeexercise)

From the iOS app: [`pauseWatchOSWorkout`](https://docs.tryterra.co/reference/streaming-api/ios-swift#pausewatchosworkout--resumewatchosworkout--stopwatchosworkout), [`resumeWatchOSWorkout`](https://docs.tryterra.co/reference/streaming-api/ios-swift#pausewatchosworkout--resumewatchosworkout--stopwatchosworkout), [`stopWatchOSWorkout`](https://docs.tryterra.co/reference/streaming-api/ios-swift#pausewatchosworkout--resumewatchosworkout--stopwatchosworkout)

```swift
import WatchKit
import TerraRTiOS

class InterfaceController: WKInterfaceController {
    var terra: Terra?

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        do {
            terra = try Terra()
            terra?.connect()
        } catch {
            print("Failed to initialize: \(error)")
        }
    }

    @IBAction func startExerciseTapped() {
        terra?.startExercise(forType: .RUNNING) { success, error in
            if success {
                print("Running exercise started")
            } else {
                print("Failed: \(error?.localizedDescription ?? "Unknown")")
            }
        }
    }

    @IBAction func pauseExerciseTapped() {
        terra?.pauseExercise()
    }

    @IBAction func resumeExerciseTapped() {
        terra?.resumeExercise()
    }

    @IBAction func stopExerciseTapped() {
        terra?.stopExercise { success, error in
            if success {
                print("Exercise stopped")
            } else {
                print("Failed: \(error?.localizedDescription ?? "Unknown")")
            }
        }
    }
}
```

***

## Stream to Terra

Once data from the wearable reaches your app, you can also send it to Terra's websocket server (the [broker](https://docs.tryterra.co/introduction/core-concepts#streaming-api)). Your backend then receives it through a [backend consumer](/streaming-api/terra-greater-than-your-backend).

To do this, use the `startRealtime` overload that accepts a `token` in place of the [local-only call](#start-streaming):

```swift
import TerraRTiOS

// Assumes terraRT is already initialized and a device is connected
// (see the sections above)

let token = "yourStreamingToken"  // Generated from your backend (see below)
let dataTypes: Set<TerraRTiOS.DataTypes> = [.HEART_RATE, .STEPS]

// Stream to BOTH your app AND Terra's websocket server
terraRT.startRealtime(
    type: .BLE,
    dataType: dataTypes,
    token: token,
    callback: { update in
        print("\(update.type ?? ""): \(update.val ?? 0) at \(update.ts ?? "")")
    },
    connectionCallback: { connected in
        print("Websocket connected: \(connected)")
    }
)
```

Pass in a token from the following endpoint, and the SDK streams the same data you were reading in your app to the broker.

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>" path="/auth/user" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>
{% endopenapi %}


# Android SDK

Connect a BLE or ANT+ wearable to your Android app with TerraRTAndroid, then stream its data to Terra.

## Install the SDK

Ensure you have the following before you begin:

1. **Android Studio**: The latest stable version.
2. **Terra Account**: Access to your Terra Developer account and API key.
3. **Gradle Dependency**: Ensure you include the TerraRT SDK in your project by adding the necessary dependencies.

   ```gradle
   implementation 'co.tryterra:terra-rtandroid:X.X.X'
   ```

   based on [the latest version on maven central](https://central.sonatype.com/artifact/co.tryterra/terra-rtandroid)

## Initialize the SDK

{% hint style="info" %}
Always initialize the `TerraRT` class to begin using the SDK.

Do so every time the app is opened or brought into the foreground.
{% endhint %}

To do this, run the [TerraRT manager initialization function](https://docs.tryterra.co/reference/streaming-api/android-kotlin#terrart) as below:

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import co.tryterra.terrartandroid.TerraRT

class MainActivity : AppCompatActivity() {
    private lateinit var terraRT: TerraRT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val developerId = "yourDeveloperId"
        val referenceId: String? = "yourReferenceId"

        terraRT = TerraRT(
            devId = developerId,
            context = this,
            referenceId = referenceId
        ) { success ->
            if (success) {
                println("TerraRT initialized successfully")
            } else {
                println("Failed to initialize TerraRT")
            }
        }
    }
}
```

## Register the phone

Register the [phone](https://docs.tryterra.co/introduction/core-concepts#streaming-api) by calling [`initConnection`](https://docs.tryterra.co/reference/streaming-api/android-kotlin#initconnection).

This connects the [phone](https://docs.tryterra.co/introduction/core-concepts#streaming-api) to Terra, allows you to use other SDK functions, and allows it to be a [producer](https://docs.tryterra.co/introduction/core-concepts#streaming-api) once a [device](https://docs.tryterra.co/introduction/core-concepts#streaming-api) is connected later on.

Use the [terraRT instance created above](#initialize-the-sdk) and call initConnection as below using an **authentication token**.

```kotlin
val token = "yourAuthToken"  // Generated from your backend

terraRT.initConnection(token) { success ->
    if (success) {
        println("Connection initialized successfully!")
    } else {
        println("Failed to initialize connection.")
    }
}
```

To generate the **token**, make the below call **from your backend**

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>" path="/auth/generateAuthToken" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>
{% endopenapi %}

## Scan for devices

Once initialized, you can scan for devices and connect to them using the TerraRT SDK.

You can scan for devices using

* BLE
* ANT+ (if supported by the Android phone used)

Start scanning for devices and let the user connect to a wearable device using [startDeviceScan](https://docs.tryterra.co/reference/streaming-api/android-kotlin#startdevicescan-with-built-in-ui).

You can choose whether to use cached devices (ones you've connected to before) or show a connection widget if no cached device is found.

```kotlin
import co.tryterra.terrartandroid.enums.Connections

// Option 1: Widget-based scan with auto-connection
terraRT.startDeviceScan(
    type = Connections.BLE,
    useCache = false,
    showWidgetIfCacheNotFound = true
) { success ->
    if (success) {
        println("Device connected successfully!")
    } else {
        println("Failed to connect to the device.")
    }
}

// Option 2: Programmatic scan with device callback
terraRT.startDeviceScan(type = Connections.BLE) { device ->
    println("Found device: ${device.deviceName}")
    // Connect to the chosen device
    terraRT.connectDevice(device) { connected ->
        println("Device connected: $connected")
    }
}
```

## Start streaming

Once the device is connected, you can start streaming real-time data such as heart rate, steps, and more.

{% hint style="info" %}
Receiving a real time data stream depends on the [device](https://docs.tryterra.co/introduction/core-concepts#streaming-api) being configured to broadcast the data it is collecting through BLE or ANT+
{% endhint %}

```kotlin
import co.tryterra.terrartandroid.enums.DataTypes

val dataTypes: Set<DataTypes> = setOf(DataTypes.HEART_RATE, DataTypes.STEPS)

// Stream data locally (no server)
terraRT.startRealtime(type = Connections.BLE, dataTypes = dataTypes) { update ->
    println("${update.type}: ${update.`val`}")
}
```

To also send data to Terra's server, see [Stream to Terra](#stream-to-terra).

## Stop streaming and disconnect

Stop the stream:

```kotlin
terraRT.stopRealtime(type = Connections.BLE)
```

Disconnect the device:

```kotlin
terraRT.disconnect(type = Connections.BLE)
```

## Full example

Manage a BLE connection and stream data:

```kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import co.tryterra.terrartandroid.TerraRT
import co.tryterra.terrartandroid.enums.Connections
import co.tryterra.terrartandroid.enums.DataTypes
import co.tryterra.terrartandroid.models.Update

class MainActivity : AppCompatActivity() {
    private lateinit var terraRT: TerraRT

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        terraRT = TerraRT(
            devId = "yourDeveloperId",
            context = this,
            referenceId = "yourReferenceId"
        ) { success ->
            if (success) {
                println("TerraRT initialized")
                connectAndStream()
            }
        }
    }

    private fun connectAndStream() {
        val token = "yourAuthToken"

        terraRT.initConnection(token) { success ->
            if (success) {
                // Scan and connect to a BLE device
                terraRT.startDeviceScan(
                    type = Connections.BLE,
                    useCache = false
                ) { scanSuccess ->
                    if (scanSuccess) {
                        // Start streaming heart rate data
                        val dataTypes = setOf(DataTypes.HEART_RATE, DataTypes.STEPS)
                        terraRT.startRealtime(
                            type = Connections.BLE,
                            dataTypes = dataTypes
                        ) { update ->
                            handleUpdate(update)
                        }
                    }
                }
            }
        }
    }

    private fun handleUpdate(update: Update) {
        println("${update.type}: ${update.`val`} at ${update.ts}")
    }

    override fun onDestroy() {
        super.onDestroy()
        terraRT.stopRealtime(type = Connections.BLE)
        terraRT.disconnect(type = Connections.BLE)
    }
}
```

## Stream to Terra

Once data from the wearable reaches your app, you can also send it to Terra's websocket server (the [broker](https://docs.tryterra.co/introduction/core-concepts#streaming-api)). Your backend then receives it through a [backend consumer](/streaming-api/terra-greater-than-your-backend).

To do this, use the `startRealtime` overload that accepts a `token` in place of the [local-only call](#start-streaming):

```kotlin
import co.tryterra.terrartandroid.TerraRT
import co.tryterra.terrartandroid.enums.Connections
import co.tryterra.terrartandroid.enums.DataTypes
import co.tryterra.terrartandroid.models.Update

// Assumes terraRT is already initialized and a device is connected
// (see the sections above)

val token = "yourStreamingToken"  // Generated from your backend (see below)
val dataTypes = setOf(DataTypes.HEART_RATE, DataTypes.STEPS)

// Stream to BOTH your app AND Terra's websocket server
terraRT.startRealtime(
    type = Connections.BLE,
    dataTypes = dataTypes,
    token = token,
    updateHandler = { update ->
        println("${update.type}: ${update.`val`} at ${update.ts}")
    },
    connectionCallback = { connected ->
        println("Websocket connected: $connected")
    }
)
```

Pass in a token from the following endpoint, and the SDK streams the same data you were reading in your app to the broker.

{% hint style="info" %}
Make sure to pass in the correct user ID in the `id` query parameter in the call below. You may retrieve that user ID using the [`getUserId`](https://docs.tryterra.co/reference/streaming-api/android-kotlin#getuserid) function in the SDK.
{% endhint %}

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>" path="/auth/user" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>
{% endopenapi %}


# React Native SDK

Connect a BLE wearable or Apple Watch to your React Native app with terra-rt, then stream its data to Terra.

## Install the SDK

1. Install the [`terra-rt`](https://www.npmjs.com/package/terra-rt) package:

```bash
npm install terra-rt
```

2. **iOS:** In your `Info.plist`, add:
   * `Privacy - Bluetooth Always Usage Description`: Justification for BLE usage
   * `Privacy - Motion Usage Description`: Justification for motion sensor usage (required if streaming accelerometer, gyroscope, or step data from the phone's built-in sensors via `Connections.APPLE`)
3. **iOS:** Run `pod install` in your `/ios` directory.
4. **Android:** Permissions are requested automatically by the SDK on initialization.

## Initialize the SDK

{% hint style="info" %}
Initialize the SDK every time the app is opened or brought into the foreground.
{% endhint %}

Set up event emitters for receiving data, then initialize:

```tsx
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import {
  initTerra, initConnection, startDeviceScan, startRealtime,
  stopRealtime, disconnect, getUserId,
  Connections, DataTypes,
} from 'terra-rt';
import type { Update, Device, SuccessMessage } from 'terra-rt';

// Set up event listeners (do this once, e.g. in useEffect)
const updateEmitter = new NativeEventEmitter(NativeModules.UpdateHandler);
updateEmitter.addListener('Update', (update: Update) => {
  console.log(`${update.type}: ${update.val}`);
});

const deviceEmitter = new NativeEventEmitter(NativeModules.DeviceHandler);
deviceEmitter.addListener('Device', (device: Device) => {
  console.log(`Found device: ${device.name}`);
});

const connectionEmitter = new NativeEventEmitter(NativeModules.ConnectionHandler);
connectionEmitter.addListener('ConnectionUpdate', (connected: boolean) => {
  console.log(`Websocket connected: ${connected}`);
});

// Initialize the SDK
const result = await initTerra('YOUR_DEV_ID', 'YOUR_REFERENCE_ID');
if (!result.success) {
  console.error('Failed to initialize:', result.error);
}
```

## Register the phone

Register the phone with Terra using an authentication token generated **from your backend**:

```tsx
const token = 'yourAuthToken'; // Generated from your backend

const connResult = await initConnection(token);
if (connResult.success) {
  console.log('Connection initialized!');
}
```

To generate the **token**, make the below call **from your backend**:

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>" path="/auth/generateAuthToken" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>
{% endopenapi %}

## Scan for devices

BLE device scanning works differently on iOS and Android:

{% tabs %}
{% tab title="Android" %}
On Android, use `startDeviceScan` which shows a built-in device picker:

```tsx
const scanResult = await startDeviceScan(Connections.BLE);
if (scanResult.success) {
  console.log('Device connected!');
}
```

{% endtab %}

{% tab title="iOS" %}
On iOS, `startDeviceScan` is not supported. Instead, use the `BLWidget` native view component:

```tsx
import { requireNativeComponent } from 'react-native';

const BLWidget = requireNativeComponent('BLWidget');

// In your JSX:
<BLWidget
  style={{ flex: 1 }}
  withCache={false}
  onSuccessfulConnection={(event) => {
    console.log('Connected:', event.nativeEvent.success);
  }}
/>
```

Render this component when you want to show the BLE scanner. It displays a list of discovered devices and handles connection automatically.
{% endtab %}
{% endtabs %}

To scan on both platforms, branch on `Platform.OS`:

```tsx
const startScanning = () => {
  if (Platform.OS === 'android') {
    startDeviceScan(Connections.BLE).then((result) => {
      console.log('Connected:', result.success);
    });
  } else {
    // Show BLWidget in your UI (see iOS tab above)
  }
};
```

## Start streaming

Once a device is connected, start streaming data. Updates arrive via the `Update` event emitter you set up earlier.

```tsx
const dataTypes = [DataTypes.HEART_RATE, DataTypes.STEPS];

// Start streaming locally (no server)
await startRealtime(Connections.BLE, dataTypes);
```

To also stream to Terra's server, see [Stream to Terra](#stream-to-terra).

## Stop streaming and disconnect

```tsx
await stopRealtime(Connections.BLE);
await disconnect(Connections.BLE);
```

## Stream from an Apple Watch

To stream data from an Apple Watch, call `connectWithWatchOS()` on the iOS companion app side, then start streaming with `Connections.WATCH_OS`:

```tsx
import { connectWithWatchOS } from 'terra-rt';

// Connect to paired Apple Watch (iOS only: rejects on Android)
await connectWithWatchOS();

// Start receiving watch data
await startRealtime(Connections.WATCH_OS, [DataTypes.HEART_RATE]);
```

{% hint style="info" %}
The watchOS app itself must be written in native Swift using the `Terra` class from the `TerraRTiOS` framework. See the [iOS SDK page](/streaming-api/ios-swift#stream-from-an-apple-watch) for the watch-side setup.
{% endhint %}

## Stream to Terra

Once data from the wearable reaches your app, you can also send it to Terra's websocket server. Your backend then receives it through a [backend consumer](/streaming-api/terra-greater-than-your-backend).

The [local stream](#start-streaming) calls `startRealtime` without a token. To also send data to Terra's server, pass a **streaming token** as the third argument:

```tsx
import { getUserId, startRealtime, Connections, DataTypes } from 'terra-rt';

const startServerStreaming = async () => {
  // 1. Get the Terra user ID
  const { userId } = await getUserId();
  if (!userId) return;

  // 2. Get a streaming token from your backend
  const tokenResponse = await fetch('YOUR_BACKEND_URL/streaming-token', {
    method: 'POST',
    body: JSON.stringify({ userId }),
  });
  const { token } = await tokenResponse.json();

  // 3. Start streaming with the token: data goes to BOTH your app and Terra's server
  const dataTypes = [DataTypes.HEART_RATE, DataTypes.STEPS];
  await startRealtime(Connections.BLE, dataTypes, token);
};
```

The `token` parameter is the only difference from local-only streaming. When provided, the SDK opens a websocket connection to Terra and relays data in real time.

Listen for websocket connection status via the `ConnectionUpdate` event:

```tsx
import { NativeEventEmitter, NativeModules } from 'react-native';

const connectionEmitter = new NativeEventEmitter(NativeModules.ConnectionHandler);
connectionEmitter.addListener('ConnectionUpdate', (connected: boolean) => {
  console.log('Websocket connected:', connected);
});
```

Your backend should generate the streaming token by calling:

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>" path="/auth/user" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>
{% endopenapi %}


# Flutter SDK

Connect a BLE wearable or Apple Watch to your Flutter app with terra\_flutter\_rt, then stream its data to Terra.

## Install the SDK

1. Add [`terra_flutter_rt`](https://pub.dev/packages/terra_flutter_rt) to your `pubspec.yaml`:

```yaml
dependencies:
  terra_flutter_rt: ^X.X.X
```

2. **iOS:** In your `Info.plist`, add:
   * `Privacy - Bluetooth Always Usage Description`: Justification for BLE usage
   * `Privacy - Motion Usage Description`: Justification for motion sensor usage (required if streaming accelerometer, gyroscope, or step data from the phone's built-in sensors via `Connection.apple`)
3. **Android:** Permissions are requested automatically by the SDK on initialization.

## Initialize the SDK

{% hint style="info" %}
Initialize the SDK every time the app is opened or brought into the foreground.
{% endhint %}

```dart
import 'package:terra_flutter_rt/terra_flutter_rt.dart';
import 'package:terra_flutter_rt/types.dart';

await TerraFlutterRt.init('YOUR_DEV_ID', 'YOUR_REFERENCE_ID');
```

## Register the phone

Register the phone with Terra using an authentication token generated **from your backend**:

```dart
final token = 'yourAuthToken'; // Generated from your backend

await TerraFlutterRt.initConnection(token);
```

{% hint style="warning" %}
Call `initConnection` on every cold start, after `init` and before scanning. The connection lives for the current app session only and is not persisted, so a full app kill clears it. Skipping this after a restart (calling only `init`) leaves scanning with no active connection, which on iOS renders `iOSScanView` as a blank screen. Each call needs a fresh token, as auth tokens are single-use.
{% endhint %}

To generate the **token**, make the below call **from your backend**:

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>" path="/auth/generateAuthToken" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/v2-bundled.yaml>
{% endopenapi %}

## Scan for devices

Two approaches depending on your needs:

### Use the built-in scan widget

On Android, this shows a native device picker. On iOS, use the `iOSScanView` widget.

```dart
import 'package:terra_flutter_rt/ios_controller.dart';

// Android: shows native picker
await TerraFlutterRt.startDeviceScan(
  Connection.ble,
  connectionCallback: (connected) {
    print('Device connected: $connected');
  },
);

// iOS: embed the native BLE scanner view in your widget tree
// (renders empty Container on Android)
iOSScanView()
```

### Scan programmatically

Discover devices one by one and connect manually:

```dart
await TerraFlutterRt.startDeviceScanToCallback(
  Connection.ble,
  (Device device) async {
    print('Found: ${device.deviceName}');
    // Connect to this device
    await TerraFlutterRt.connectDevice(device);
  },
  connectionCallback: (connected) {
    print('Connection status: $connected');
  },
);
```

## Start streaming

Once a device is connected, start streaming data to your app via a callback:

```dart
void onUpdate(Update data) {
  print('${data.type.datatypeString}: ${data.val}');
}

await TerraFlutterRt.startRealtimeToApp(
  Connection.ble,
  [DataType.heartRate, DataType.steps],
  onUpdate,
);
```

To stream to Terra's server instead, see [Stream to Terra](#stream-to-terra).

## Stop streaming and disconnect

```dart
await TerraFlutterRt.stopRealtime(Connection.ble);
await TerraFlutterRt.disconnect(Connection.ble);
```

## Stream from an Apple Watch

To stream data from an Apple Watch:

```dart
// Connect to paired Apple Watch (iOS only: returns false on Android)
final connected = await TerraFlutterRt.connectWatchOS();

if (connected) {
  // Start receiving watch data
  await TerraFlutterRt.startRealtimeToApp(
    Connection.watchOs,
    [DataType.heartRate],
    onUpdate,
  );
}
```

{% hint style="info" %}
The watchOS app itself must be written in native Swift using the `Terra` class from the `TerraRTiOS` framework. See the [iOS SDK page](/streaming-api/ios-swift#stream-from-an-apple-watch) for the watch-side setup.
{% endhint %}

You can also control workout sessions on the watch from your Flutter app:

```dart
await TerraFlutterRt.resumeWatchOSWorkout();
await TerraFlutterRt.pauseWatchOSWorkout();
await TerraFlutterRt.stopWatchOSWorkout();
```

## Stream to Terra

Once data from the wearable reaches your app, you can send it to Terra's websocket server. Your backend then receives it through a [backend consumer](/streaming-api/terra-greater-than-your-backend).

The [local stream](#start-streaming) uses `startRealtimeToApp`. To send data to Terra's server instead, use `startRealtimeToServer` with a **streaming token**:

```dart
import 'package:terra_flutter_rt/terra_flutter_rt.dart';
import 'package:terra_flutter_rt/types.dart';

Future<void> startServerStreaming() async {
  // 1. Get the Terra user ID
  final userId = await TerraFlutterRt.getUserId();
  if (userId == null) return;

  // 2. Get a streaming token from your backend
  final token = await fetchStreamingTokenFromBackend(userId);

  // 3. Start streaming to Terra's server
  await TerraFlutterRt.startRealtimeToServer(
    Connection.ble,
    [DataType.heartRate, DataType.steps],
    token,
  );
}
```

{% hint style="info" %}
**Flutter has separate functions** for local and server streaming:

* `startRealtimeToApp`: streams to a local callback only (no server)
* `startRealtimeToServer`: streams to Terra's websocket server only (no local callback)

To receive data both locally and on your server, call `startRealtimeToApp` for the local callback and have your backend consume from the [Terra websocket](/streaming-api/terra-greater-than-your-backend).
{% endhint %}

Your backend should generate the streaming token by calling:

{% openapi src="<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>" path="/auth/user" method="post" %}
<https://raw.githubusercontent.com/tryterra/openapi/refs/heads/master/dist/core/rt-bundled.yaml>
{% endopenapi %}


# Wear OS

Stream data from a Wear OS watch to your Android app with the TerraWearOS library.

Use the TerraWearOS library in your Wear OS app, together with [TerraRTAndroid](https://github.com/tryterra/TerraRTAndroid) in your phone app.\
It uses a Bluetooth connection to stream data to your Android phone, which then streams it to Terra over websockets.

## Install the library

You may add it as a dependency on your app gradle file as: `implementation 'co.tryterra:terra-wearos:X.X.X'`

{% hint style="info" %}
Please include the following in your AndroidManifest:

```xml
<queries>
    <package android:name="com.google.android.wearable.healthservices" />
</queries>
```

{% endhint %}

## Create the Terra instance

You will need to instantiate the `Terra` class as follows:

```kotlin
terra = Terra(context: Context, streamDataSet: Set<StreamDataTypes>)
```

When you create this class, the user is prompted for `Body Sensor`, `Location`, and `Activity Recognition` permissions.

**Arguments**

* `context: Context`: The app context you are calling this class from
* `streamDataSet: Set<StreamDataTypes>`: The set of datatypes you wish to stream data for. Takes a set of `StreamDataTypes` enum.

## Start Bluetooth discovery

To put your device in discovery mode, run

```kotlin
terra.startBluetoothDiscovery(callback: (Boolean) -> Unit)
```

You can now search for this device with the TerraRTAndroid package to initialise the connection.

The callback will be called when the connection is completed with either `true` (successful) or `false` (unsuccessful).

## Start streaming

Start streaming data to your phone:

```kotlin
terra.startStream()
```

Stop streaming with:

```kotlin
terra.stopStream()
```

## Stream an exercise

You may also perform exercises on the device, and have the data streamed to your phone.

You will first have to prepare the exercise by:

```kotlin
terra.prepareExercise(type: ExerciseTypes, dataTypes: Set<DataTypes>, shouldEnableGPS: Boolean, callback: (Boolean) -> Unit)
```

This only warms up the sensors.

**Arguments**

* `type: ExerciseTypes`: The type of exercise you wish to prepare for. Takes an `ExerciseTypes` enum.
* `dataTypes: Set<DataTypes>`: The datatypes from this exercise you wish to retrieve. Takes a set of `DataTypes` enum
* (Optional) `shouldEnableGPS: Boolean`: Defaults to false. Determines whether the location sensor is warmed up.
* (Optional) `callback`: A callback function indicating when and if the preparation of the exercise is completed and successful **(recommended)**

After preparation, you may then start an exercise:

```kotlin
terra!!.startExercise(
  type: ExerciseTypes,
  dataTypes: Set<DataTypes>,
  shouldEnableGPS: Boolean,
  shouldEnableAutoPauseAndResume: Boolean,
)
```

**Arguments**

* `type: ExerciseTypes`: The type of exercise you wish to prepare for. Takes an `ExerciseTypes` enum.
* `dataTypes: Set<DataTypes>`: The datatypes from this exercise you wish to retrieve. Takes a set of `DataTypes` enum
* (Optional) `shouldEnableGPS: Boolean`: Defaults to false. Allow for location data streaming
* (Optional) `shouldEnableAutoPauseAndResume: Boolean`: Defaults to false. Allow for the watch to automatic pause and resume exercise.

Starting the exercise automatically starts streaming data to your phone.

You can also pause, resume, and stop the exercise:

```kotlin
terra.stopExercise()
terra.resumeExercise()
terra.pauseExercise()
```

## Payload format

The data will arrive in your websocket server in the following format:

```json
{
  "op":5,
  "d":
    {
      "ts": <String> (In ISOFormat Date Form)
       "val": <Double>
       "d" <Array<Double>>
    },
    "uid": <String> (user ID)
    "seq": <Int>,
    "t": <String> (Datatype name: Exactly the same as the name of `DataTypes` enum)
}
```

`ts` is the timestamp of the record.

For Exercises, `t` will be a concatenation of the `ExerciseTypes` ENUM and `DataTypes` ENUM.\
For example, if you are performing a `RUNNING` exercise, while streaming `HEART_RATE` and `STEPS`, two different payloads will be streamed to your websocket connection with types: `RUNNING_HEART_RATE` and `RUNNING_STEPS`


# Backend consumer

Set up and manage a consumer connection to the Terra WebSocket service to receive real-time health data.

This page covers connecting to the WebSocket, sending heartbeats, authenticating, and receiving data.

## Set up a consumer connection

A consumer connection delivers your developer ID's real-time data stream. To set up your consumer connection to the Terra WebSocket service, follow the steps below.

**WebSocket endpoint:** `wss://ws.tryterra.co/connect`

***

## Connect to the WebSocket

Once you open a WebSocket connection to the server, you will immediately receive an `Op 2 HELLO` payload. This payload contains the `heartbeat_interval` value (in milliseconds), which the client will use to maintain the connection.

Example payload:

```json
{
  "op": 2,
  "d": {
    "heartbeat_interval": 40000
  }
}
```

After receiving this payload, the client must start sending heartbeat messages, as described below.

***

## Send heartbeats

{% hint style="info" %}
To keep the WebSocket connection alive, the client **needs** to send regular heartbeats.

This lets the server know the connection is still active and waiting for data.
{% endhint %}

To send a heartbeat, send the following payload:

```json
{
  "op": 0
}
```

You'll always receive the following response (acknowledging your heartbeat):

```json
{
  "op": 1
}
```

{% hint style="danger" %}

* The first heartbeat should be sent after `heartbeat_interval * jitter` milliseconds, where jitter is a random value between 0 and 1.
* After the first heartbeat, continue sending heartbeats **at most** at the interval specified in the HELLO payload.
* If no `HEARTBEAT_ACK` is received, the client should close the connection and establish a new one.
* If the server does not receive a heartbeat for more than one `heartbeat_interval`, it will close the connection with code **4005**.
  {% endhint %}

***

## Authenticate the connection

{% hint style="warning" %}
You must send an IDENTIFY payload **within 15 seconds** of connecting. If the server does not receive IDENTIFY in time, it will close the connection with code **4000**.
{% endhint %}

Once heartbeating is set up, the client must authenticate the connection by sending an `IDENTIFY` payload containing a token.

IDENTIFY payload:

```json
{
  "op": 3,
  "d": {
    "token": "your_developer_token_here",
    "type": 1
  }
}
```

The `type` field specifies the connection type:

| Type | Name      | Description                                                                                  |
| ---- | --------- | -------------------------------------------------------------------------------------------- |
| `0`  | USER      | Producer connection (mobile SDKs sending data). Uses a token from `POST /auth/user`.         |
| `1`  | DEVELOPER | Consumer connection (your backend receiving data). Uses a token from `POST /auth/developer`. |

For consumer connections (this guide), use `type: 1` with a developer token.

{% hint style="info" %}
**Tokens are single-use.** Each token is deleted from the server after a successful IDENTIFY. If your connection drops, you must generate a new token before reconnecting.
{% endhint %}

{% hint style="warning" %}
**Consumer session limit.** A per-developer cap limits concurrent consumer connections. During the current rollout the cap is **1**, so opening a second consumer connection closes that new connection with code **4002**. Close the previous session first. The cap is a server-side setting and may be raised, so don't hard-code an assumption of exactly one consumer.
{% endhint %}

When authentication is successful, the server will respond with an `Op 4 READY` message:

```json
{
  "op": 4
}
```

***

## Receive data

Once the connection is established and authenticated, data from your connected users will be streamed to you in real time.

When new data is available, an `Op 5 DISPATCH` payload is sent:

```json
{
  "op": 5,
  "d": {
    "ts": "2022-05-04T10:26:11.268507+01:00",
    "val": 95
  },
  "uid": "user_id_here",
  "seq": 73,
  "t": "HEART_RATE"
}
```

Each dispatch contains:

* `op`: Opcode `5` (DISPATCH).
* `uid`: The Terra user ID of the user whose device produced this data.
* `t`: The data type (e.g., `"HEART_RATE"`, `"STEPS"`, `"ACCELERATION"`, `"ECG"`, `"HRV"`, `"CALORIES"`, `"LOCATION"`, `"GYROSCOPE"`, etc.).
* `seq`: A **sparse**, time-ordered cursor. Values generally increase over time, but gaps between consecutive values are normal and do **not** indicate lost data (treat it as a cursor, not a counter). Two readings produced in the same instant may arrive in either order. Use it to order DISPATCHes and as the `after` bound for [replay](#request-missed-data).
* `d`: The data payload:
  * `ts`: ISO 8601 timestamp of the reading.
  * `val`: Scalar value (e.g., heart rate BPM, step count). Present for single-value types.
  * `d`: Array of doubles (e.g., `[x, y, z]` for accelerometer/gyroscope, or `[lat, lng]` for location). Present for multi-axis types.

***

## Request missed data

If your connection drops and you miss some data, you can request it using the REPLAY command once you reconnect.

To backfill the gap on reconnect:

1. Re-IDENTIFY, then wait for the first live DISPATCH and note its `seq` (call it `firstLive`).
2. Send a REPLAY with `after` = the last `seq` you processed before the drop, and `before` = `firstLive`.
3. Process the replayed DISPATCHes (they arrive as op 5 payloads), then resume handling live data.

If no live DISPATCH has arrived yet, there's nothing to backfill. REPLAY once one does.

**REPLAY Command (Op 7)**

```json
{
  "op": 7,
  "d": {
    "after": 28,
    "before": 43
  }
}
```

* `after` (required): Replay messages with sequence numbers **greater than** this value, typically the last `seq` you successfully processed before disconnecting.
* `before` (required): Replay messages with sequence numbers **less than** this value. Set it to the `seq` of the first live DISPATCH you receive after reconnecting, so you backfill exactly the gap. Both bounds are required: a REPLAY without `before` returns no messages.

{% hint style="info" %}
Bounds are **exclusive**: `after: 28, before: 43` replays sequence numbers 29 through 42.

Replayed messages arrive as standard DISPATCH (op 5) payloads.
{% endhint %}

{% hint style="info" %}
Replay reads from Terra's data warehouse, so a payload becomes replayable a few seconds after it is delivered live. If a REPLAY returns fewer messages than you expect, wait a moment and request it again. There is currently no retention limit on replayable data, though this may change in future.
{% endhint %}

***

## Close codes

The server may close your WebSocket connection with one of the following custom close codes:

| Code     | Reason                                  | What to do                                                                                                          |
| -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **4000** | Identify expected but was not received  | Send IDENTIFY within 15 seconds of connecting                                                                       |
| **4001** | Improper token has been passed          | Token is invalid or expired. Generate a new one                                                                     |
| **4002** | Consumer session limit reached          | Another consumer session is already active for your developer ID (current cap). Close it first                      |
| **4003** | Multiple IDENTIFY payloads received     | Don't send IDENTIFY more than once per connection                                                                   |
| **4004** | Invalid opcode was received             | You sent an opcode the server doesn't recognize, or one not valid for your session type (e.g. SUBMIT on a consumer) |
| **4005** | Heartbeat expected but was not received | Send heartbeats within the `heartbeat_interval` window                                                              |

The server may also close with the standard WebSocket codes **1000** (normal closure), **1003** (a malformed frame was received), or **1011** (internal server error).

For reconnect logic: **4000**, **4003**, **4004**, and **1003** signal a client-side bug. Fix your client rather than reconnecting, since a blind retry just loops on the same error. The rest are safe to reconnect after the remedy above (for **4001**, always mint a fresh token; for **4002**, close the other session first).

## Next steps

* See every opcode, payload field, data type and close code in the [WebSocket protocol reference](https://docs.tryterra.co/reference/streaming-api/websocket-reference).


# Data types

The data types the RT SDKs can stream, and what decides whether a device sends them.

{% hint style="info" %}
Streaming carries **realtime, roughly per-second signals only**. For longer-span data (workouts, sleep, daily totals, body, nutrition) use the [Unified API](/unified-api/getting-started) instead.
{% endhint %}

## What you can request

The RT SDKs accept the following values in the `DataTypes` enum. You pass a set of them to `startRealtime` (or to the `Terra` constructor on Wear OS), and each streamed payload is labelled with the matching name in its `t` field.

| Group              | Data types                                                                  |
| ------------------ | --------------------------------------------------------------------------- |
| **Cardiac**        | `HEART_RATE`, `HRV`, `RR_INTERVAL`, `ECG`                                   |
| **Movement**       | `STEPS`, `STEPS_CADENCE`, `DISTANCE`, `SPEED`, `FLOORS_CLIMBED`, `ACTIVITY` |
| **Cycling**        | `POWER`, `BIKE_CADENCE`                                                     |
| **Motion sensors** | `ACCELERATION`, `GYROSCOPE`                                                 |
| **Energy**         | `CALORIES`, `MET`                                                           |
| **Position**       | `LOCATION`                                                                  |

***

## What you actually receive

**Requesting a data type is not the same as receiving it.** Three things have to line up before a value reaches your backend:

1. **The wearable broadcasts it.** Receiving a realtime stream depends on the device being configured to broadcast that signal over BLE, ANT+, or a supported custom Bluetooth protocol. A device that does not broadcast a signal cannot stream it, no matter what you request.
2. **The connection type carries it.** A BLE heart-rate strap and a Wear OS watch expose very different sets of sensors.
3. **You asked for it.** Only the data types in the set you pass to `startRealtime` are streamed.

If you request a data type and see nothing on the stream, check them in that order: silence almost always means the device is not broadcasting that signal, not that the connection is broken.

{% hint style="warning" %}
Most heart-rate straps broadcast cardiac signals only. A chest strap will not give you `STEPS`, `LOCATION`, or `FLOORS_CLIMBED` however you configure the SDK. Those come from a watch or from the phone's own sensors. Design your app to degrade gracefully when a data type never arrives.
{% endhint %}

***

## Connection types

The `Connections` enum selects which transport you are scanning and streaming over.

| Connection    | What it covers                                                           |
| ------------- | ------------------------------------------------------------------------ |
| `BLE`         | Bluetooth Low Energy wearables: heart-rate straps and compatible watches |
| `ANT`         | ANT+ wearables, where the Android phone's hardware supports ANT+         |
| `WEAR_OS`     | A Wear OS watch running your companion app                               |
| `WATCH_OS`    | An Apple Watch, over WatchConnectivity, requires a companion watchOS app |
| `APPLE`       | Apple platform sources                                                   |
| `ANDROID`     | The Android phone's own sensors                                          |
| `ALL_DEVICES` | Any connected device                                                     |

Availability varies by platform: ANT+ is Android-only and depends on the handset, and `WATCH_OS` requires a companion watchOS app because React Native cannot build one directly. See the SDK page for your platform: [iOS](/streaming-api/ios-swift), [Android](/streaming-api/android), [React Native](/streaming-api/react-native), or [Flutter](/streaming-api/flutter).

***

## Wear OS labels data types differently

On Wear OS, streams started as part of an exercise are labelled with the exercise type **and** the data type, concatenated. Streaming `HEART_RATE` and `STEPS` during a `RUNNING` exercise produces two payload streams typed `RUNNING_HEART_RATE` and `RUNNING_STEPS`, not `HEART_RATE` and `STEPS`.

Parse the `t` field accordingly if your consumer handles both Wear OS and BLE producers.

***

## Working out what a device broadcasts

Terra does not gate or filter by device. The broker passes payloads through opaquely and labels them with the `data_type` your producer supplied. What arrives is decided entirely by the wearable's own broadcast profile.

To find out what a specific device supports:

* **Check the manufacturer's specification** for the BLE services or ANT+ profiles it advertises.
* **Scan and observe.** Connect the device with the RT SDK, request a broad set of data types, and log which ones actually produce payloads. This is the most reliable answer for a given firmware version.
* **Use a test user.** From the **Streaming** page of the [Terra dashboard](https://dashboard.tryterra.co/dashboard/streaming) you can stream synthetic data without hardware, which separates "my consumer is wrong" from "this device does not broadcast that".


# Overview

Manage coaches and athletes, and read team training data with the Teams API.

## Introduction

The Teams API allows developers to interact with team-based fitness tracking data used in sports training and monitoring. You can manage user accounts, retrieve performance metrics, and integrate with various fitness tracking providers.

### User management

#### Coaches

Coaches are central to the Teams API, as they manage athletes and their associated data.

**Creating a Coach**

To begin using, you'll need to register a coach account.

This involves providing necessary credentials and integration specifics related to the provider you're integrating with (e.g., VALD, Catapult).

*Endpoint*: `POST /coaches`

*Description*: Registers a new coach with the specified provider.

**Required Fields**:

* `reference_id`: Your internal identifier for the coach.
* `provider`: The integration provider (e.g., `VALD`, `CATAPULT`).
* Provider-specific authentication fields (e.g., `client_id`, `client_secret`, `token`).

**Note**: After creating a coach, you'll receive a `coach_id` generated by the server, which you'll use for subsequent operations.

**Deleting a Coach**

If you need to remove a coach and all associated data, you can delete the coach account.

*Endpoint*: `DELETE /coaches/{coachId}`

*Description*: Deletes a coach and all associated athletes, activities, and tests.

**Required Parameter**:

* `coachId`: The unique identifier of the coach to be deleted.

**Warning**: This action is irreversible and will remove all data related to the coach.

#### Athletes

Athletes are managed under coaches and represent the individuals whose performance data you're tracking.

**Managing Athletes**

While athletes are typically synced from the provider's system, you can retrieve and update athlete information as needed.

*Endpoint to List Athletes*: `GET /coaches/{coachId}/athletes`

*Description*: Retrieves all athletes under a specific coach.

**Required Parameter**:

* `coachId`: The unique identifier of the coach whose athletes you want to list.

### Getting data

#### Activities

Activities represent performance sessions or events recorded by athletes.

**Fetching Activities**

You can retrieve all activities recorded by athletes under a specific coach.

*Endpoint*: `GET /coaches/{coachId}/activities`

*Description*: Retrieves activities within a specified time range for all athletes under the coach.

**Required Parameter**:

* `coachId`: The unique identifier of the coach.

**Optional Query Parameters**:

* `start_time`: Start of the time range (ISO 8601 format).
* `end_time`: End of the time range (ISO 8601 format).

**Fetching Activity Schemas**

To understand the structure of activity metrics available, you can fetch the activity metrics schema.

*Endpoint*: `GET /coaches/{coachId}/activities/metrics/schema`

*Description*: Returns the schema of activity metrics for the specified coach.

**Required Parameter**:

* `coachId`: The unique identifier of the coach.

#### Tests

Tests are specific assessments or measurements conducted with athletes.

**Fetching Tests**

You can retrieve all tests conducted by athletes under a specific coach.

*Endpoint*: `GET /coaches/{coachId}/tests`

*Description*: Retrieves tests within a specified time range for all athletes under the coach.

**Required Parameter**:

* `coachId`: The unique identifier of the coach.

**Optional Query Parameters**:

* `start_time`: Start of the time range (ISO 8601 format).
* `end_time`: End of the time range (ISO 8601 format).

### Additional features

#### Webhooks

Webhooks allow your application to receive real-time notifications when certain events occur, such as coach registration or athlete data updates.

**Available Webhooks**:

* `coach.registered`: Triggered when a new coach is registered.
* `athlete.registered`: Triggered when one or more athletes are registered.

**Setting Up Webhooks**:

You'll need to configure your endpoint to receive webhook events and handle them appropriately. Ensure your endpoint is secure and can process the data received.

#### Handling enums

The API uses various enumerations (enums) to represent specific sets of values for certain fields, such as `Sport`, `Position`, `Movement`, etc.

**Examples of Enums**:

* `Sport`: Indicates the type of sport (e.g., `FOOTBALL`, `BASKETBALL`).
* `Side`: Indicates the side of the body (`LEFT`, `RIGHT`, `BOTH`).
* `MetricType`: Indicates the type of metric (`FORCE`, `VELOCITY`, `POWER`).

**Usage**:

When processing data from the API, you'll encounter integer values representing these enums. Refer to the enum definitions provided in the API documentation to interpret these values correctly.

#### Integrating with providers

The Teams API supports integration with various fitness tracking providers. Each provider may have specific requirements for authentication and data retrieval.

**Fetching Provider Details**:

*Endpoint*: `GET /integrations/detailed`

*Description*: Returns detailed information about available providers, including required login fields and logos.

**Provider-Specific Fields**:

When creating a coach or integrating with a provider, you'll need to supply provider-specific authentication fields such as `client_id`, `client_secret`, or `token`.

**Example Providers**:

* **VALD**: May require `client_id` and `client_secret`.
* **Catapult**: May require an API `token`.

**Note**: Always refer to the provider's documentation for the most accurate and up-to-date integration requirements.

### Conclusion

This guide provides an overview of how to get started with the Teams API for managing coaches, athletes, and retrieving performance data. By following the endpoints and guidelines outlined above, you can effectively integrate the Teams API into your application.

For detailed information on each endpoint, including request and response formats, please refer to the API reference documentation.

If you have any questions or need further assistance, feel free to reach out to our support team.


# Supported integrations

The team-sport platforms the Teams API connects to, their enum values, and where to get credentials for each.

The Teams API connects to the platforms below. Use the enum value as the `provider` when you create a coach.

<table data-full-width="true"><thead><tr><th>Integration</th><th>Enum value</th><th>Data</th><th>Devices</th><th>Getting credentials</th></tr></thead><tbody><tr><td>VALD</td><td>VALD</td><td>Tests</td><td><p><a href="https://valdperformance.com/products/forceframe">ForceFrame</a> (Isometric strength tester)</p><p><a href="https://valdperformance.com/products/forcedecks">ForceDecks</a> (Force plates)</p><p><a href="https://valdperformance.com/products/dynamo">DynaMo</a> (Dynamometer)</p><p><a href="https://valdperformance.com/products/nordbord">NordBord</a> (Hamstring testing)</p></td><td><a href="https://support.vald.com/hc/en-au/articles/15973572185625-Integrate-your-PMS-AMS-with-VALD-Hub#client-id">https://support.vald.com/hc/en-au/articles/15973572185625-Integrate-your-PMS-AMS-with-VALD-Hub#client-id</a></td></tr><tr><td>Catapult</td><td>CATAPULT</td><td>Activities</td><td><a href="https://www.catapult.com/solutions/vector-pro">Vector</a> (GPS tracker vests)</td><td><a href="https://support.catapultsports.com/hc/en-us/articles/360002186896-API-Tokens">https://support.catapultsports.com/hc/en-us/articles/360002186896-API-Tokens</a></td></tr><tr><td>Kinexon</td><td>KINEXON</td><td>Activities</td><td><a href="https://kinexon-sports.com/technology/player-tracking/">Player tracking</a> (IMUs, LPS, GPS, Video tracking)</td><td>Get in touch with your Product Success Manager at Kinexon</td></tr><tr><td>GymAware</td><td>GYMAWARE</td><td>Tests</td><td><a href="https://gymaware.com/gymaware-rs/">GymAware RS</a> (Velocity-Based Training device)<br><a href="https://gymaware.com/product/flex-barbell-tracker/">Flex</a> (Barbell tracker)</td><td><a href="https://gymaware.com/gymaware-cloud-api-integration-guide/#tokens">https://gymaware.com/gymaware-cloud-api-integration-guide/#tokens</a></td></tr><tr><td>Sparta Science</td><td>SPARTASCIENCE</td><td>Tests</td><td><a href="https://spartascience.com/">Force plates</a></td><td><a href="https://success.spartascience.com/en/knowledge/integrations-and-api-access">https://success.spartascience.com/en/knowledge/integrations-and-api-access</a></td></tr></tbody></table>


# Overview

What a Terra integration partner is, and why health platforms connect their APIs to Terra.

### What is a Terra integration partner?

<figure><img src="https://464213908-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVGMJVuZnZyOtvV4b53cY%2Fuploads%2Fgit-blob-2024b07d86bc6277798bbb4ec64a82f5a74dfa23%2Fintegration-partners-overview.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

Integration partners are health platforms (like Garmin, Fitbit, or Strava) that have their APIs connected to Terra. This gives developers building on Terra access to 100+ platforms through a single integration on their side.

So if you become an integration partner, Terra sits between your API and the applications built on top of your data. It handles authentication, data retrieval, formatting, and delivery to developers. You configure the integration once. Terra keeps it running.

### Why become an integration partner?

**1 - Reach more developers without extra engineering work**

Any developer building on Terra can access your data without you having to build or maintain a direct integration with them. You provide your API configuration. Terra builds the integration and handles ongoing delivery. Your team is not responsible for maintaining it or handling individual developer requests.

**2 - Access to AI-powered health experiences**

Terra is the data layer for a growing number of AI health apps. If your data is on Terra, it is accessible to developers building AI-powered features in health, fitness, coaching, and research.

**3 - You control what is shared**

You decide which data types are accessible and under what conditions. Terra does not access data beyond what you configure.

**4 - Structured onboarding for sensitive data**

The integration process follows a defined flow designed for handling health data responsibly, including authentication, token management, and delivery.


# How the integration works

How Terra connects to your platform through authentication, API pull and webhooks.

Setting up a Terra integration involves three things:

1. **Authentication**: how your users allow Terra to read their data
2. **API pull**: how Terra retrieves data from your platform (always required)
3. **Webhooks**: how your platform notifies Terra when new data is available (optional but highly recommended)

```
  ┌─────────────────────┐                    ┌─────────────────────┐
  │                     │  ─── API pull ───▶ │                     │
  │   YOUR PLATFORM     │                    │     TERRA API       │
  │                     │  ─── Webhooks ───▶ │                     │
  └─────────────────────┘                    └─────────────────────┘
```

### Authentication

When one of your users wants to connect their account to a Terra-powered app, they go through your platform's own login and consent screen. They approve what data to share. Terra never sees their password.

The result is a token: a secure key that Terra stores and uses to request data on that user's behalf. Terra handles renewing it automatically when it expires.

OAuth 2.0 is the recommended path. If your platform supports it, you can fast-track your application by filling in the form at [partner.tryterra.co](https://partner.tryterra.co/).

{% hint style="info" %}
**No API or not using OAuth 2.0?** You can still become a partner. Reach out to us at <providers@tryterra.co> and we'll work with you directly.
{% endhint %}

### API pull

Terra calls your API to retrieve user data. This always happens when a user first connects: Terra pulls their recent history so developers have data to work with immediately. After that, Terra continues to call your API on a regular schedule unless you support webhooks (see below).

What Terra needs from you:

* The endpoint URLs for each data type you support (sleep, activity, daily stats, etc.)
* How to authenticate the request
* How to pass a date range and user ID
* A full example of what your API returns

Terra takes care of transforming your response format into a standardised schema that developers can use.

### Webhooks (optional but highly recommended)

If your platform can send a notification to Terra each time a user syncs their device or logs data, Terra will use that instead of regularly polling your API. This means faster, real-time data delivery and less load on your API.

How it works: your system sends a POST request to Terra's endpoint each time an event occurs. Terra verifies the request, identifies the user, and processes the data.

What Terra needs from you:

* Confirmation that your system can POST to Terra's webhook endpoint
* A full example of the event payload you send
* Which field in the payload contains the `user_id` (so Terra can match the event to the right user)
* A shared secret for request verification (Terra uses HMAC)

You send data in your own format. Terra handles the mapping.


# Submitting an application

Apply to become a Terra integration partner through the self-serve form, and what to prepare first.

{% hint style="info" %}
**Not using OAuth 2.0, or no traditional API?** You can still become a partner. Email us at <providers@tryterra.co> and we'll guide you through the right path.
{% endhint %}

If your platform supports OAuth 2.0, the fastest way to get started is through Terra's self-serve application form at [partner.tryterra.co](https://partner.tryterra.co/). It walks you through the configuration Terra needs to connect to your API, step by step.

#### What you'll configure in the form

**OAuth 2.0 URLs**

Your authorization endpoint (where users log in and approve access), your token endpoint (where Terra exchanges the code for a token), and optionally a refresh or revocation URL.

**Client credentials**

Your `client_id` and `client_secret`: the credentials Terra uses to identify itself when calling your OAuth endpoints. You generate these when you register Terra as an authorized app in your developer portal.

**User ID extraction**

After a user connects, Terra needs to know which user it's dealing with. You tell Terra where to find that ID: either directly in the token response, or by pointing to a user-info endpoint and the field to read from.

**Scopes**

Scopes are the permissions a user grants when they connect. You define which scopes Terra should request, which are required for each data type, and how granted scopes are returned in the response.

**Data endpoints**

For each data type your platform supports, you provide the endpoint URL, HTTP method, and the scopes required to access it.

#### Before you start

Make sure you have the following ready:

* [ ] OAuth 2.0 authorization and token endpoints
* [ ] Client credentials (`client_id` and `client_secret`) for your OAuth app
* [ ] A clear way to identify users after token exchange
* [ ] Your scope model documented
* [ ] Endpoint details for the data types you support

After you submit, Terra's team reviews your configuration and we'll get back to you shortly.

#### Contacts and links

* Support and questions: <providers@tryterra.co>
* [Integration Partners Terms of Service](https://tryterra.co/integration-partner-terms)


# Overview

Convert lab report and DXA scan PDFs into structured, standardized biomarker data via a simple REST API.

## Terra Lab Reports API

Upload a clinical lab report or a DXA body-composition/bone-density scan and receive structured biomarker data: extracted, standardized, and delivered to your webhook or available via REST.

Both go to the same endpoint. Terra identifies which it received and tells you in `report_type`.

### Key features

* **Multi-Format Upload**: Upload clinical lab reports or DXA scans as PDF, PNG, JPEG, GIF, WebP, or HEIC, as one file or one photo per page (up to 20 files and 50 MB)
* **Automatic Report-Type Detection**: Terra classifies each upload as a lab report or a scan; no parameter to set, and the result is reported in `report_type`
* **Site-Scoped Scan Results**: Scan measurements carry the anatomical site they were taken at, so the same measure at fifteen places stays fifteen distinct results
* **Biomarker Standardization**: Results are fuzzy-matched against a 4,100+ biomarker reference dataset, producing a canonical `biomarker` slug and UCUM-compliant unit codes. Values stay in the units the lab printed.
* **Reference Ranges with Context**: Extracted ranges include demographic context (sex, age, pregnancy status, menstrual cycle phase)
* **Async Processing**: Upload returns immediately with an upload ID; results arrive via webhook or polling, typically within 3 to 5 minutes
* **Webhook Delivery**: Full session payload is delivered automatically to your configured destination on completion
* **Flexible Querying**: List and filter sessions by reference ID, upload ID, report type, and date range

### API endpoints

| Method | Endpoint                             | Description              |
| ------ | ------------------------------------ | ------------------------ |
| POST   | `/v2/reports`                        | Upload a lab report      |
| GET    | `/v2/reports`                        | List sessions            |
| GET    | `/v2/reports/{session_id}`           | Retrieve session details |
| POST   | `/v2/reports/{session_id}/reprocess` | Reprocess a session      |
| DELETE | `/v2/reports/{session_id}`           | Delete a session         |

Base URL: `https://access.tryterra.co/api`

### Documentation

1. [Quickstart](/lab-reports/quickstart): Upload, poll, and retrieve in 3 steps
2. [Core concepts](/lab-reports/core-concepts): Session lifecycle, data model, async processing
3. [API reference](/lab-reports/api-reference): Full endpoint specifications
4. [Webhook payload](/lab-reports/webhook-payload): Payload format and field specs
5. [Biomarker reference](/lab-reports/biomarker-reference): Standardization, UCUM codes, common biomarkers
6. [Best practices](/lab-reports/best-practices): Error handling, idempotency, limits

To see the API in a working app, start from the [Lab Reports example app](https://docs.tryterra.co/developer-tools/example-apps/terra-panel): `terra examples clone lab-reports-web-app my-app`.


# Pricing

The Lab Reports API is a paid add-on to the Quick Start plan, with usage measured in Lab Reports credits.

## The add-on

The Lab Reports API turns lab reports into structured data, from blood, urine and stool tests to hormone panels, DEXA body-composition scans and more. It is available as an add-on to the Quick Start plan for **$499/month**. Activate it from the dashboard under **Settings → Plans & Pricing → Additional Products**.

Without the add-on, uploads return `403` with the code `entitlement_required`.

## Lab Reports credits

Your subscription includes **100,000 Lab Reports credits per month**, in addition to your 100,000 Unified API credits. Lab Reports credits are a separate balance: lab report usage never draws down your Unified API credits, and Unified API usage never draws down your Lab Reports credits.

There is no separate sandbox for Lab Reports. Uploads from every environment, including Testing, count toward your Lab Reports credits.

<table><thead><tr><th>About</th><th valign="top">Biomarker</th></tr></thead><tbody><tr><td><strong>What it is</strong></td><td valign="top">A biomarker is one result extracted from a lab report or DXA scan (e.g. LDL-C, HbA1c, CRP), returned in a consistent, machine-readable format. Values are reported in the units the lab printed.</td></tr><tr><td><strong>How it's measured</strong></td><td valign="top">Each extracted result counts toward usage, including results that don't match a biomarker in Terra's reference dataset. On a DXA scan, each anatomical site is a separate result. Reports that fail processing are not counted.</td></tr><tr><td><strong>Cost</strong></td><td valign="top"><p>10 Lab Reports credits per biomarker.</p><p>Your 100,000 included Lab Reports credits cover 10,000 biomarkers each month.</p></td></tr></tbody></table>

## Beyond the included credits

Tiered pricing applies beyond your included Lab Reports credits, billed at the end of each billing cycle:

| **Total Monthly Lab Reports Credits Consumed** | **Cost per Additional Credit** |
| ---------------------------------------------- | ------------------------------ |
| 0 - 100,000                                    | $0 (Included in add-on)        |
| 100,001 - 1,000,000                            | $0.005                         |
| 1,000,001+                                     | $0.003                         |

See [Pricing](/unified-api/pricing) for the Quick Start plan and the other add-on products.




---

[Next Page](https://docs.tryterra.co/llms-full.txt/1)

