Terra Docs
Dashboard
  • Docs
  • API Reference
  • Changelog
  • Getting Started
    • What is Terra API?
    • Account setup and API keys
    • Core concepts
  • Health & Fitness API
    • Overview
    • Quickstart
    • Integration setup
      • Understanding sources and destinations
      • Setting up data sources
      • Setting up data destinations
        • Webhooks
        • SQL database (Postgres, MySQL)
        • Supabase
        • Cloud storage (S3, GCP)
        • Queuing services (SQS, Kafka)
      • Customising data types
      • Dedicated data source API keys
      • Understanding Terra environments
    • User authentication
      • Authentication flow
      • Implementation (Terra widget)
      • Implementation (Custom UI)
      • Handling authentication events
      • Customising authentication redirects
    • Managing user health data
      • Receiving health data updates (events)
      • Requesting historical health data (REST API requests)
      • Writing data
    • Mobile-only sources
      • iOS (Swift)
      • Android (Kotlin)
      • React Native
      • Flutter
    • Troubleshooting
    • Pricing
  • User Engagement
    • Health Scores
  • Streaming API
    • Overview
    • Wearable -> Your app
      • iOS (Swift)
      • Android
    • Your app -> Terra
      • iOS (Swift)
      • Android
    • Terra -> Your backend
  • Teams API
  • Biomarkers API - Upcoming
Powered by GitBook
On this page
  • Key steps to setup Health & Fitness API
  • Next steps

Was this helpful?

  1. Health & Fitness API

Quickstart

Learn how to receive data events in just 3 steps

PreviousOverviewNextIntegration setup

Last updated 8 days ago

Was this helpful?

Key steps to setup Health & Fitness API

Follow this short tutorial to set up event-based health data delivery via Webhooks. Learn how Terra manages user authentication and can automatically send new user data, simplifying your integration. (Other methods, like requesting historical data, are covered in the detailed guides.

1

Integration Setup

A. Add Data Sources from your Terra Dashboard

  • First you need to select your data sources on your Terra dashboard. This determines:

    • (a) What data sources are available for end-users to chose on the Terra auth widget.

    • What data sources are automatically synced to your data destination via events.

B. Add a Data Destination in your Terra Dashboard

  • The Health & Fitness API is event-based, so the Data Destinations are where you will receive payload events:

    • (a) New health data updates

    • (b) Authentication events, de-auth events, etc.

How to setup a Webhook destination?

Webhook.site

  • Copy Your unique URL that is automatically generated when you enter the site.


Your own Webhook endpoint on your local machine

  • First create a web server that runs locally on your computer (see code block).

  • If you are using ngrok, running ngrok http {PORT_NUMBER} will expose your server to the internet and return its URL.

import flask

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

C. Obtain your API Key & Dev-ID from your Terra Dashboard

2

User Authentication

  • Next you need to authenticate a user via the API to a data source (e.g. to Oura, Fitbit, Withings).

  • Terra simplifies this by allowing you to generate a pre-built authentication widget session (by running the following code).

  • Copy/Paste the widget session url into web browser. To test the authentication flow, you can choose a data sources (e.g. Fitbit), and complete the flow.

import requests

url = "https://api.tryterra.co/v2/auth/generateWidgetSession"
data = {
      "reference_id": "my_first_connection",
      "auth_success_redirect_url": "text",
      "auth_failure_redirect_url": "text",
}
headers = {
    "dev-id": "<YOUR-DEV-ID>", 
    "x-api-key": "<YOUR-API-KEY>"
    "Content-Type": "application/json"
}
response = requests.post(url, data=data, headers=headers)
response.raise_for_status()
widget_url = response["url"]  # e.g. "https://widget.tryterra.co/session/344d475f-296a-489a-a88c-54183671dafd",
const axios = require('axios');
const url = 'https://api.tryterra.co/v2/auth/generateWidgetSession';
const data = {
reference_id: 'my_first_connection',
auth_success_redirect_url: 'text',
auth_failure_redirect_url: 'text',
};
const headers = {
'dev-id': '',
'x-api-key': '',
'Content-Type': 'application/json',
};
axios
.post(url, data, { headers })
.then((response) => {
const widget_url = response.data.url;
console.log('Widget URL:', widget_url);
})
.catch((error) => {
console.error('Error generating widget session:', error.response?.data || error.message);
});
CLI
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": "text",
      "auth_failure_redirect_url": "text",
  }'

3

Receive data updates

  • Terra automatically sends new data to your server (e.g. webhook endpoint) when it becomes available from your users' wearables.

  • If you're using your own Webhook destination, the following code is an example of how you can handle Webhooks.

python
import logging
import flask
from flask import request

import requests

logging.basicConfig(level=logging.INFO)
_LOGGER = logging.getLogger("app")

app = flask.Flask(__name__)

@app.route("/consumeTerraWebhook", methods=["POST"])
def consume_terra_webhook() -> flask.Response:
    data = request.get_json()
    _LOGGER.info(
        "Received webhook for user %s of type %s",
        data.get("user", {}).get("user_id"),
        data["type"])
    # you can now use the incoming data in your app
    # handleData(data)
    
if __name__ == "__main__":
    app.run(host="localhost", port=8080)
javascript
const express = require("express");
const bodyParser = require("body-parser");

const app = express();

// Parse raw JSON bodies
app.use(
  bodyParser.raw({
    inflate: true,
    limit: "4000kb",
    type: "application/json",
  })
);

// Webhook endpoint
app.post("/consumeTerraWebhook", (req, res) => {
  res.sendStatus(200); // Respond to Terra immediately

  try {
    const data = JSON.parse(req.body.toString("utf8"));
    console.log("Received Terra Webhook Data:");
    console.log(JSON.stringify(data, null, 2));
  } catch (err) {
    console.error("Failed to parse webhook payload:", err.message);
  }
});

// Start server
const port = 3000;
app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

Next steps

Now that you understand the basics, move onto onto our guides for detailed documentation on the Health & Fitness API

Using you can generate a temporary webhook destinations for testing.

Then, expose your server to the internet with a tool such as and start receiving payloads.

webhook.site
ngrok
2 minute video walkthrough of Quickstart
Screenshot of the Terra dashboard with a red box highlighting the button to obtain API credentials