> ## Documentation Index
> Fetch the complete documentation index at: https://openwearables.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Add a Wearable Provider Integration

> Add a new fitness data provider to Open Wearables. Covers Strategy, Factory, and Template Method patterns for OAuth, workout, and webhook handlers.

# How to Add a New Provider Integration

This guide walks you through the process of adding a new fitness data provider (e.g. Strava, Samsung Health, Xiaomi, WHOOP) to the OpenWearables platform. The architecture uses design patterns like **Strategy**, **Factory**, and **Template Method** to make adding new providers straightforward and consistent.

## Architecture Overview

Before diving into implementation, understand the main components:

1. **Strategy** - Defines the provider's identity, capabilities, and wires together all components
2. **Strategy Factory** - Central management of strategy instantiation (used by routes)
3. **OAuth Handler** - Manages authentication flow (if provider uses cloud API)
4. **Workouts Handler** - Fetches and normalizes workout/activity data
5. **247 Data Handler** - Fetches continuous health metrics (sleep, recovery, HR, etc.)
6. **Webhook Handler** - Receives and processes incoming push events from the provider

Each provider declares its data delivery modes via `ProviderCapabilities`:

| Capability | Description | Example providers |
| - | - | - |
| `rest_pull` | Usually historical REST API | Oura, Whoop, Strava, Suunto, Withings |
| `client_sdk` | Data delivered via mobile SDK client | Apple, Samsung, Google |
| `file_import` | File-based data import | Apple Health |
| `webhook_callback` | Provider-initiates async export delivered to our webhook | Garmin backfill |
| `webhook_stream` | Provider pushes full data payload in every webhook | Garmin, Suunto |
| `webhook_ping` | Provider sends a lightweight notification; actual data must be fetched via REST | Oura, Strava, Fitbit, Polar, Withings |
| `webhook_registration_api` | Provider exposes an API to programmatically register webhook subscriptions. When `False`, subscriptions must be configured manually in the provider's developer portal. | Oura, Withings |
| `webhook_subscription_per_user` | Subscriptions are created with each connection's own bearer token, so one exists per active connection instead of a single app-level registration. Requires `webhook_registration_api=True`. | Withings |

> [!NOTE]
>
> `webhook_stream` and `webhook_ping` are mutually exclusive. Use `webhook_stream` when the provider embeds the complete record in the webhook body (Garmin, Suunto). Use `webhook_ping` when the webhook is only a trigger and you must call the REST API to retrieve the actual data (Oura, Strava, Fitbit, Polar, Withings).

![Custom providers architecture showing Strategy, OAuth, Workouts, 247 Data, and Webhook Handler components](https://mintcdn.com/momentum-64cd1fcc/a3MKkR50UjvA29DQ/images/providers/custom-providers-architecture.png?fit=max\&auto=format\&n=a3MKkR50UjvA29DQ\&q=85\&s=4b9e69db3fee273efb1172ddb5ae90b3)

***

## Prerequisites

Before starting, gather the following information about your provider:

> [accordion] Provider API Information
>
> * Base API URL (e.g. `https://cloudapi.suunto.com`)
> * Authentication method (usually OAuth 2.0)
> * Available data endpoints (activities, workouts, health metrics)
> * Rate limits and pagination

> [accordion] OAuth Configuration (if applicable)
>
> * Authorization URL
> * Token exchange URL
> * Required scopes
> * PKCE required (yes/no)
> * Credentials being sent via `Authorization` header or request body
> * Client credentials (ID and Secret)
> * Where redirect URL should be registered

> [accordion] Data Format
>
> * Workout/activity data structure
> * Timestamp format (Unix, ISO 8601, etc.)
> * Available metrics (heart rate, distance, calories, etc.)
> * Workout type mappings

Please, remember to provide `svg` icon for a new provider. It should be named `<lowercase_provider_name>.svg` and be placed in `/backend/app/static/provider-icons`.

***

## Step 1: Create Provider Directory Structure

Create a new directory for your provider in `backend/app/services/providers/`.

For a provider named **Suunto**, create:

```bash theme={null}
backend/app/services/providers/suunto/
├── __init__.py
├── strategy.py        # Provider strategy + capabilities + coverage declaration
├── coverage.py        # Declares what data the provider emits (single source of truth)
├── oauth.py           # OAuth handler (skip if PUSH-only with no REST API)
├── workouts.py        # Workout/activity data handler
├── data_247.py        # 24/7 continuous health data (optional)
└── webhook_handler.py # Incoming webhook handler (optional, if webhook_stream or webhook_ping)
```

> [!TIP]
>
> Use lowercase for the provider name in directory and file names to maintain consistency with existing providers.

***

## Step 2: Implement the Strategy Class

The strategy class is the entry point for your provider. It defines the provider's identity, declares its **capabilities**, and initializes its components.

Create `backend/app/services/providers/suunto/strategy.py`:

```python theme={null}
from app.services.providers.base_strategy import BaseProviderStrategy, ProviderCapabilities, ProviderCoverage
from app.services.providers.suunto.coverage import HEALTH_SCORES, SLEEP_FIELDS, TIMESERIES, WORKOUT_FIELDS
from app.services.providers.suunto.oauth import SuuntoOAuth
from app.services.providers.suunto.workouts import SuuntoWorkouts


class SuuntoStrategy(BaseProviderStrategy):
    """Suunto provider implementation."""

    def __init__(self):
        super().__init__()
        
        # Initialize OAuth component (skip for SDK/XML-only providers)
        self.oauth = SuuntoOAuth(
            user_repo=self.user_repo,
            connection_repo=self.connection_repo,
            provider_name=self.name,
            api_base_url=self.api_base_url,
        )
        
        # Initialize workouts component
        self.workouts = SuuntoWorkouts(
            workout_repo=self.workout_repo,
            connection_repo=self.connection_repo,
            provider_name=self.name,
            api_base_url=self.api_base_url,
            oauth=self.oauth,
        )

        # Webhook handler — only set if webhook_stream or webhook_ping (see below)
        # self.webhooks = SuuntoWebhookHandler(...)

    @property
    def name(self) -> str:
        """Unique identifier for the provider (lowercase)."""
        return "suunto"

    @property
    def api_base_url(self) -> str:
        """Base URL for the provider's API."""
        return "https://cloudapi.suunto.com"

    @property
    def capabilities(self) -> ProviderCapabilities:
        """Declare what data delivery modes this provider supports."""
        return ProviderCapabilities(
            rest_pull=True,
            webhook_stream=True,  # Suunto delivers full payload in every webhook
        )

    @property
    def coverage(self) -> ProviderCoverage:
        """Declare what data this provider emits (powers /api/v1/meta/coverage)."""
        return ProviderCoverage(
            timeseries=TIMESERIES,
            workout_fields=WORKOUT_FIELDS,
            sleep_fields=SLEEP_FIELDS,
            health_scores=HEALTH_SCORES,
        )
```

### Key Points:

* `name`: Must be unique and lowercase (used in URLs and database)
* `api_base_url`: Used by the API client to construct requests
* `display_name`: Optional, shown in UI (defaults to `name.capitalize()`)
* `capabilities`: **Required** — tells the unified router and sync scheduler how this provider delivers data
* `coverage`: declares what data the provider emits; pass through all four constants from `coverage.py` (see below)
* Set `self.webhooks = None` (default) if your provider has no incoming webhooks
* Set `self.oauth = None` for SDK/file-upload-only providers like Apple Health

![SuuntoStrategy extends BaseProviderStrategy: shared repositories, abstract and default properties in the base class, and the properties and components Suunto implements](https://mintcdn.com/momentum-64cd1fcc/a3MKkR50UjvA29DQ/images/providers/provider-strategy.png?fit=max\&auto=format\&n=a3MKkR50UjvA29DQ\&q=85\&s=f087f2b5507c6f2f2b9e56e8381bf180)

> [!TIP]
>
> Inherited `BaseProviderStrategy` will init all required repositories so you don't need to take care about database manipulations. You can read more about repositories role in our [System Overview](https://openwearables.io/docs/architecture/system-overview.md).

***

### Declare data coverage (`coverage.py`)

`coverage.py` is the single source of truth for what your provider emits. It powers the public [`GET /api/v1/meta/coverage`](https://openwearables.io/docs/api-reference) endpoint and the Data Coverage matrix, and the `coverage` property above reads from it.

Create `backend/app/services/providers/suunto/coverage.py`:

```python theme={null}
from app.schemas.enums import SeriesType
from app.schemas.enums.health_score_category import HealthScoreCategory

# Mapping tables (handler key → SeriesType) are imported and used directly by
# data_247.py / workouts.py, so TIMESERIES is derived from them and never drifts.
ACTIVITY_SERIES: dict[str, SeriesType] = {
    "steps": SeriesType.steps,
    "energy": SeriesType.energy,
}

TIMESERIES: frozenset[SeriesType] = frozenset(
    {
        *ACTIVITY_SERIES.values(),        # /v1/activity
        SeriesType.resting_heart_rate,    # single inline emission
    }
)

# EventRecordDetail fields your handlers populate
WORKOUT_FIELDS: frozenset[str] = frozenset({"energy_burned", "distance", "moving_time_seconds"})
SLEEP_FIELDS: frozenset[str] = frozenset({"sleep_total_duration_minutes", "sleep_deep_minutes"})
HEALTH_SCORES: frozenset[HealthScoreCategory] = frozenset({HealthScoreCategory.RECOVERY})
```

Rules:

* Move any `key → SeriesType` mapping that lives in `data_247.py`/`workouts.py` into `coverage.py` and import it back, so the mapping is defined once and `TIMESERIES` is derived from it.
* Single inline `series_type=SeriesType.X` emissions may stay in the handler, but `X` must appear in `TIMESERIES`.
* Declare all four constants; use `frozenset()` for layers your provider doesn't emit (e.g. a workouts-only provider has an empty `TIMESERIES`).

A guard test scans your implementation and **fails** if it emits a `SeriesType` or sets an `EventRecordDetail` field not declared here — and asserts the strategy's `coverage` property exposes all four constants:

```bash theme={null}
cd backend && uv run pytest tests/providers/test_provider_coverage.py -k suunto -q
```

```
4 passed in 0.42s
```

***

## Step 3: Implement OAuth Handler (PULL providers)

If your provider uses OAuth 2.0 for authentication, implement the OAuth handler.

Create `backend/app/services/providers/suunto/oauth.py`:

```python theme={null}
import httpx
from app.config import settings
from app.schemas import (
    AuthenticationMethod,
    OAuthTokenResponse,
    ProviderCredentials,
    ProviderEndpoints,
)
from app.services.providers.templates.base_oauth import BaseOAuthTemplate


class SuuntoOAuth(BaseOAuthTemplate):
    """Suunto OAuth 2.0 implementation."""

    @property
    def endpoints(self) -> ProviderEndpoints:
        """OAuth endpoints for authorization and token exchange."""
        return ProviderEndpoints(
            authorize_url="https://cloudapi-oauth.suunto.com/oauth/authorize",
            token_url="https://cloudapi-oauth.suunto.com/oauth/token",
        )

    @property
    def credentials(self) -> ProviderCredentials:
        """OAuth credentials from environment variables."""
         return ProviderCredentials(
            client_id=settings.suunto_client_id or "",
            client_secret=(settings.suunto_client_secret.get_secret_value() if settings.suunto_client_secret else ""),
            redirect_uri=settings.suunto_redirect_uri,
            default_scope=settings.suunto_default_scope,
            subscription_key=(
                settings.suunto_subscription_key.get_secret_value() if settings.suunto_subscription_key else ""
            ),
        )

    # OAuth configuration
    use_pkce: bool = False  # Set True if provider requires PKCE
    auth_method: AuthenticationMethod = AuthenticationMethod.BASIC_AUTH  # or BODY

    def _get_provider_user_info(
        self, 
        token_response: OAuthTokenResponse, 
        user_id: str
    ) -> dict[str, str | None]:
        # implement your method here
        pass
```

> [!NOTE]
>
> Here you can also create all provider-specific methods, like `_register_user` in Polar's case.

### Configuration Options:

> [card] use\_pkce
>
> Set to `True` if provider requires PKCE (Proof Key for Code Exchange). Garmin enforces PKCE, Polar and Suunto don't.

> [card] auth\_method
>
> * `BASIC_AUTH`: Credentials in Authorization header (Polar, Suunto)
> * `BODY`: Credentials in request body (Garmin)

### Add Environment Variables:

Add your OAuth credentials to `.env`:

```bash theme={null}
SUUNTO_CLIENT_ID=your_client_id
SUUNTO_CLIENT_SECRET=your_client_secret
SUUNTO_REDIRECT_URI=https://yourdomain.com/api/v1/oauth/suunto/callback
SUUNTO_DEFAULT_SCOPE=activity:read_all
```

And update `backend/app/config.py`:

```python theme={null}
class Settings(BaseSettings):
    # ... existing settings ...
    
    # Suunto OAuth
    suunto_client_id: str | None = None
    suunto_client_secret: SecretStr | None = None
    suunto_redirect_uri: str = "http://localhost:8000/api/v1/oauth/suunto/callback"
    suunto_default_scope: str = "activity:read_all"
```

***

## Step 4: Implement Workouts Handler

The workouts handler fetches and normalizes workout data from the provider's API.

Create `backend/app/services/providers/suunto/workouts.py`:

```python theme={null}
from datetime import datetime
from decimal import Decimal
from typing import Any
from uuid import UUID, uuid4

from app.database import DbSession
from app.schemas import EventRecordCreate, EventRecordDetailCreate, EventRecordMetrics
from app.services.providers.templates.base_workouts import BaseWorkoutsTemplate


class SuuntoWorkouts(BaseWorkoutsTemplate):
    """Suunto workouts implementation."""

    def _extract_dates(self, start_timestamp: int, end_timestamp: int) -> tuple[datetime, datetime]:
        """Extract start and end dates from timestamps."""
        start_date = datetime.fromtimestamp(start_timestamp / 1000)
        end_date = datetime.fromtimestamp(end_timestamp / 1000)
        return start_date, end_date

    def _build_metrics(self, raw_workout: SuuntoWorkoutJSON) -> EventRecordMetrics:
        hr_data = ...
        heart_rate_avg = ...
        heart_rate_max = ...
        steps_count = ...
        steps_avg = ...

        return {
            "heart_rate_min": ...
            "heart_rate_max": ...
            "heart_rate_avg": heart_rate_avg,
            "steps_min": steps_count,
            "steps_max": steps_count,
            "steps_avg": steps_avg,
            "steps_total": steps_count,
        }

    def _normalize_workout(
        self,
        raw_workout: SuuntoWorkoutJSON,
        user_id: UUID,
    ) -> tuple[EventRecordCreate, EventRecordDetailCreate]:
        """Normalize Suunto workout to EventRecordCreate."""
        workout_id = uuid4()

        workout_type = get_unified_workout_type(raw_workout.activityId)

        start_date, end_date = self._extract_dates(raw_workout.startTime, raw_workout.stopTime)
        duration_seconds = int(raw_workout.totalTime)

        source_name = ...

        device_id = ...

        metrics = self._build_metrics(raw_workout)

        workout_create = EventRecordCreate(
            category="workout",
            type=workout_type.value,
            source_name=source_name,
            device_id=device_id,
            duration_seconds=duration_seconds,
            start_datetime=start_date,
            end_datetime=end_date,
            id=workout_id,
            provider_id=str(raw_workout.workoutId),
            user_id=user_id,
        )

        workout_detail_create = EventRecordDetailCreate(
            record_id=workout_id,
            **metrics,
        )

        return workout_create, workout_detail_create

    def _build_bundles(
        self,
        raw: list[SuuntoWorkoutJSON],
        user_id: UUID,
    ) -> Iterable[tuple[EventRecordCreate, EventRecordDetailCreate]]:
        """Build event record payloads for Suunto workouts."""
        for raw_workout in raw:
            record, details = self._normalize_workout(raw_workout, user_id)
            yield record, details

    def load_data(
        self,
        db: DbSession,
        user_id: UUID,
        **kwargs: Any,
    ) -> bool:
        """Load data from Suunto API."""
        response = self.get_workouts_from_api(db, user_id, **kwargs)
        workouts_data = response.get("payload", [])
        workouts = [SuuntoWorkoutJSON(**w) for w in workouts_data]

        for record, details in self._build_bundles(workouts, user_id):
            event_record_service.create(db, record)
            event_record_service.create_detail(db, details)

        return True
```

### Key Methods to Implement:

**1. \_normalize\_workout()**

**Most important!** Convert provider's data format to OpenWearables [unified schema](https://openwearables.io/docs/architecture/unified-data-model.md).

**2. \_extract\_dates()**

Handle provider-specific timestamp formats (Unix, ISO 8601, custom strings)

**3. \_build\_metrics()**

Creates statistics for Workout.

**4. \_build\_bundles()**

Optimize query by bundling workout records into packages.

**5. load\_data()**

Main sync method that orchestrates fetching and saving data

> [!WARNING]
>
> There are also utils modules, like `app/backend/services/providers/api_client.py`, which provides utilities for making oauth api requests.

### 24/7 data handler (`data_247.py`)

Continuous metrics (sleep, recovery, HR, steps) live in a `Base247DataTemplate`
subclass. The sync orchestrator calls one entry point, `load_and_save_all`, and
every provider returns the same type from it: a `Sync247Result`.

Build the result with `sync_run()` rather than assembling a dict. Each `step` is
one data type: it commits or rolls back, logs, records what was written, and
keeps a failure in one data type from aborting the rest of the sync.

```python theme={null}
from datetime import datetime
from uuid import UUID

from app.database import DbSession
from app.services.providers.sync_247_result import Sync247Result
from app.services.providers.templates.base_247_data import Base247DataTemplate


class Suunto247Data(Base247DataTemplate):
    def load_and_save_all(
        self,
        db: DbSession,
        user_id: UUID,
        start_time: datetime | str | None = None,
        end_time: datetime | str | None = None,
        is_first_sync: bool = False,
    ) -> Sync247Result:
        # Parses ISO strings, applies the default window, forces UTC-aware bounds.
        start_dt, end_dt = self.resolve_window(start_time, end_time, default_days=28)

        run = self.sync_run(db, user_id)

        with run.step("sleep") as step:
            saved, skipped = self.load_and_save_sleep(db, user_id, start_dt, end_dt)
            step.record(saved, skipped=skipped)

        with run.step("activity_samples", commit=True) as step:
            samples = self.normalize_activity_samples(
                self.get_activity_samples(db, user_id, start_dt, end_dt), user_id
            )
            step.record(self.save_activity_samples(db, user_id, samples))

        run.log_summary()
        return run.result
```

Rules:

* **Key each step by data type**, in the provider's own vocabulary (`sleep`,
  `recovery`, `activity_samples`, `daily_activity`, or a specific metric name).
  Don't invent per-provider key suffixes like `*_synced`.
* **Return `WriteCounts` from every save path you can.** `timeseries_service.bulk_create_samples`
  and `health_score_service.bulk_create` already do, so pass their return value
  straight through instead of narrowing it to `int` or reporting `len(samples)`.
  That is what makes the sync log say "12 new, 3 updated" instead of just a total.
* A plain `int` is accepted where the write path can't report a split (sleep
  sessions merged one at a time, say). It counts toward `result.rows_written`, just
  not toward `inserted`/`updated`.
* `step` options: `commit=True` to commit after a successful step, `savepoint=True`
  to confine a failed write to a nested transaction, `capture=True` to also
  report the failure to Sentry, `accumulate=True` when the same data type is
  written once per chunk of the window (a per-day endpoint, for example).
* Pass `fatal=(ProviderConnectionError,)` to `sync_run()` for errors that invalidate the
  whole run (an expired token) instead of one data type.
* Call `run.expect("sleep", ...)` up front if your steps are conditional, so a
  data type nothing arrived for stays in the result as `skipped` rather than
  disappearing from it.
* Providers whose 24/7 data only arrives by webhook don't override the method at
  all; the base returns an empty result.

The orchestrator reads `result.rows_written` for the headline item count,
`result.inserted` / `result.updated` for the split, `result.all_failed` to decide
whether the run failed, and `result.as_dict()` for the sync-log payload.

***

## Step 5: Create Workout Type Mapping

Create a mapping file to convert provider-specific workout types to unified types.

Create `backend/app/constants/workout_types/suunto.py`:

```python theme={null}
"""Suunto activity type to OpenWearables unified workout type mapping."""
from app.schemas.workout_types import WorkoutType

SUUNTO_WORKOUT_TYPE_MAPPINGS: list[tuple[int, str, WorkoutType]] = [
    (0, "Walking", WorkoutType.WALKING),
    (1, "Running", WorkoutType.RUNNING),
    (2, "Cycling", WorkoutType.CYCLING),

    # [...]
}

SUUNTO_ID_TO_UNIFIED: dict[int, WorkoutType] = {
    activity_id: unified_type for activity_id, _, unified_type in SUUNTO_WORKOUT_TYPE_MAPPINGS
}

SUUNTO_ID_TO_NAME: dict[int, str] = {activity_id: name for activity_id, name, _ in SUUNTO_WORKOUT_TYPE_MAPPINGS}


def get_unified_workout_type(suunto_activity_id: int) -> WorkoutType:
  return SUUNTO_ID_TO_UNIFIED.get(suunto_activity_id, WorkoutType.OTHER)

def get_activity_name(suunto_activity_id: int) -> str:
    """Get the Suunto activity name for a given ID."""
    return SUUNTO_ID_TO_NAME.get(suunto_activity_id, "Unknown")
```

> [!WARNING]
>
> Review the existing unified workout types in your system before mapping. You may need to add new unified types to accommodate provider-specific activities.

***

## Step 6: Register Provider in Factory

Add your new provider to the factory so it can be instantiated by the system.

Edit `backend/app/services/providers/factory.py`:

```python theme={null}
from app.services.providers.apple.strategy import AppleStrategy
from app.services.providers.base_strategy import BaseProviderStrategy
from app.services.providers.garmin.strategy import GarminStrategy
from app.services.providers.polar.strategy import PolarStrategy
from app.services.providers.suunto.strategy import SuuntoStrategy


class ProviderFactory:
    """Factory for creating provider instances."""

    def get_provider(self, provider_name: str) -> BaseProviderStrategy:
        match provider_name:
            case "apple":
                return AppleStrategy()
            case "garmin":
                return GarminStrategy()
            case "suunto":
                return SuuntoStrategy()
            case "polar":
                return PolarStrategy()
            case _:
                raise ValueError(f"Unknown provider: {provider_name}")
```

> [!NOTE]
>
> Factory will be used by routes endpoints to fetch correct strategy.

***

## Step 7: Add Provider to Schema Enums

Update the `ProviderName` enum to include your new provider.

Edit `backend/app/schemas/oauth.py`:

```python theme={null}
from enum import Enum


class ProviderName(str, Enum):
    """Supported fitness data providers."""
    
    APPLE = "apple"
    GARMIN = "garmin"
    POLAR = "polar"
    SUUNTO = "suunto"
```

This enables:

* Type validation in API endpoints
* Auto-generated API documentation with provider options
* Enum-based routing

***

## Step 8: Test Your Integration

Now test your implementation with these steps:

### 1. Test OAuth Flow (if applicable)

```bash Start OAuth theme={null}
curl -X GET "http://localhost:8000/api/v1/oauth/suunto/authorize?user_id=YOUR_USER_ID"
```

```json Response theme={null}
{
  "authorization_url": "https://cloudapi-oauth.suunto.com/oauth/authorize?response_type=code&client_id=...",
  "state": "random_state_string"
}
```

Visit the authorization URL in your browser, authorize, and verify the callback works.

### 2. Test Data Sync

```bash Sync All Data theme={null}
curl -X POST "http://localhost:8000/api/v1/providers/suunto/users/YOUR_USER_ID/sync" \
  -H "X-Open-Wearables-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json"
```

```json Response theme={null}
{
  "success": true,
  "async": true,
  "task_id": "58fd1f21-1768-49ea-bcb8-3876b76ed4f7",
  "message": "Sync task queued for suunto. Check task status for results."
}
```

### 3. Verify Database

Check that workouts are saved correctly:

```sql theme={null}
SELECT * FROM event_records 
WHERE user_id = 'YOUR_USER_ID' 
  AND provider_id IS NOT NULL
ORDER BY created_at DESC
LIMIT 10;
```

### 4. Check Logs

Monitor logs for errors:

```bash theme={null}
docker compose logs -f app
```

If you started the API outside Docker, follow the terminal where the local server is running.

***

## Step 9 (Optional): Implement Webhook Handler (PUSH flow)

If your provider delivers data via incoming webhooks, implement a `BaseWebhookHandler` subclass and wire it into your strategy.

The unified router at `POST /api/v1/providers/{provider}/webhooks` automatically delegates all requests to `strategy.webhooks` — no new routes needed.

### Understand the delivery mode

First decide how your provider delivers webhook data:

> [card] Full payload (push)
>
> Provider sends the complete data in the webhook body. `dispatch()` saves records directly.
> **Example: Garmin**

> [card] Notify-only
>
> Provider sends a lightweight notification with user ID + event type. You must fetch actual data via REST inside `dispatch()`.
> **Example: Oura, Strava, Fitbit**

Reflect this in `capabilities` inside your strategy:

```python theme={null}
# Full-payload stream (Garmin/Suunto-style) — historical pull + live webhook stream
return ProviderCapabilities(rest_pull=True, webhook_stream=True)

# Notify-only ping (Oura/Strava-style) — REST pull + webhook triggers refetch
return ProviderCapabilities(rest_pull=True, webhook_ping=True)

# REST-only — no webhooks
return ProviderCapabilities(rest_pull=True)
```

### Create the webhook handler

Create `backend/app/services/providers/suunto/webhook_handler.py`:

```python theme={null}
from typing import Any

from fastapi import Request

from app.config import settings
from app.database import DbSession
from app.services.providers.templates.base_webhook_handler import BaseWebhookHandler
from app.utils.exceptions import InvalidInputError


class SuuntoWebhookHandler(BaseWebhookHandler):
    """Webhook handler for Suunto push events."""

    def __init__(self):
        super().__init__("suunto")

    def verify_signature(self, request: Request, body: bytes) -> bool:
        """Verify the incoming request is authentically from the provider.
        
        Use the appropriate scheme for your provider:
        - HMAC-SHA256: use self._verify_hmac_sha256(secret, body, provided_sig)
        - Plain token: use self._verify_token(expected, provided)
        - Header check: inspect request.headers directly
        """
        sig = request.headers.get("x-hmac-sha256-signature", "")
        secret = settings.suunto_webhook_secret.get_secret_value() if settings.suunto_webhook_secret else ""
        return self._verify_hmac_sha256(secret, body, sig)

    def parse_payload(self, body: bytes) -> dict[str, Any]:
        """Parse the raw webhook body into a Python dict / Pydantic model."""
        import json
        try:
            return json.loads(body)
        except (json.JSONDecodeError, ValueError) as exc:
            raise InvalidInputError("Invalid JSON body") from exc

    def dispatch(self, db: DbSession, payload: dict[str, Any]) -> dict[str, Any]:
        """Route the payload to the appropriate service method.
        
        For webhook_stream (full-payload): save records directly or enqueue a Celery task.
        For webhook_ping (notify-only): fetch actual data via REST then save.
        """
        event_type = payload.get("type", "unknown")
        
        # Enqueue async processing so we respond within the provider's timeout window
        # process_push.delay(payload, request_trace_id=...)
        
        return {"status": "accepted", "event_type": event_type}

    def supported_event_types(self) -> list[str]:
        return ["WORKOUT_CREATED"]

    def handle_challenge(self, request: Request) -> dict[str, Any]:
        """Handle GET-based subscription verification (if your provider requires it).
        
        Override only if your provider uses a GET challenge/response handshake
        (like Strava hub.challenge or Oura verification_token).
        Without an override the router answers 501.
        """
        token = request.query_params.get("hub.challenge", "")
        return {"hub.challenge": token}
```

> [!NOTE]
>
> `BaseWebhookHandler` provides two signature-verification helpers so you never reimplement cryptographic primitives:
>
> * `_verify_hmac_sha256(secret, body, provided_signature)` — for HMAC-SHA256 providers (Oura, Fitbit)
> * `_verify_token(expected, provided)` — for plain shared-secret header/query-param verification

> [!NOTE]
>
> If your provider does not sign its requests, or signs them with a key you cannot get, authenticate them with a random secret in the callback path, as Strava does:
>
> * in the handler, set `requires_callback_token = True`; the token is derived from `SECRET_KEY` per provider
> * in the webhook service, register `callback_url("<provider>")` from `app/utils/webhook_callback.py`, and pass every callback URL you log or return through `redact_callback_url`
> * a provider already registered without a token needs a one-off re-registration on upgrade, as `backend/scripts/data_migrations/register_strava_token_callback.py` does for Strava
>
> The unified router serves `/providers/{provider}/webhooks/{callback_token}`, and `BaseWebhookHandler.authenticate_callback` rejects every POST, GET and HEAD whose token is missing or wrong with `401`.

### Wire the handler into your strategy

```python theme={null}
# In suunto/strategy.py
from app.services.providers.suunto.webhook_handler import SuuntoWebhookHandler

class SuuntoStrategy(BaseProviderStrategy):
    def __init__(self):
        super().__init__()
        # ... other components ...
        self.webhooks = SuuntoWebhookHandler()

    @property
    def capabilities(self) -> ProviderCapabilities:
        return ProviderCapabilities(
            rest_pull=True,
            webhook_stream=True,
        )
```

That's all — no new route files needed. The unified router at `/api/v1/providers/suunto/webhooks` will route all POST and GET requests to your handler automatically.

> [!NOTE]
>
> `GET /api/v1/providers/{provider}/webhooks` → `strategy.webhooks.handle_challenge(request)`\
> `POST /api/v1/providers/{provider}/webhooks` → `strategy.webhooks.handle(request, body, db)`

### Automatic webhook registration (optional)

Some providers expose an API to register webhook subscriptions programmatically (e.g. Oura). For these, you can have subscriptions registered automatically whenever an admin switches the provider's live sync mode to `webhook` — no manual setup in the developer portal required.

To enable this:

1. Set `webhook_registration_api=True` in your strategy's `ProviderCapabilities`.
2. Implement `register_subscriptions(callback_url)` on your webhook service (wired as `self.webhook_service` in the strategy) to call your provider's subscription registration API. It should be idempotent — skip existing subscriptions, create missing ones.

```python theme={null}
class MyProviderStrategy(BaseProviderStrategy):
    def __init__(self) -> None:
        super().__init__()
        self.webhook_service = MyProviderWebhookService()

    @property
    def capabilities(self) -> ProviderCapabilities:
        return ProviderCapabilities(
            rest_pull=True,
            webhook_ping=True,
            webhook_registration_api=True,
        )
```

When an admin changes the sync mode via `PUT /api/v1/oauth/providers/{provider}`, the settings service hands the new mode to `strategy.apply_live_sync_mode(mode)`, which dispatches the `reconcile_provider_webhooks` Celery task so the request is not blocked on the provider's API. The task registers on `webhook` and deletes on `pull`. The callback URL is derived from `API_BASE_URL`: `{API_BASE_URL}/api/v1/providers/{provider}/webhooks`.

Implement `deregister_subscriptions()` on your webhook service on top of the list/delete methods it already has — that is the `pull` half, and without it no events stop arriving when an admin switches back to periodic pull. Override `apply_live_sync_mode()` on the strategy only if reconciliation cannot go through that task at all.

```python theme={null}
class MyProviderWebhookService(BaseWebhookService):
    async def deregister_subscriptions(self) -> list[WebhookOperationResult]:
        """Delete every subscription this application holds."""
        subscriptions = await self.list_subscriptions()  # raises on an API failure
        return [await self.delete_subscription(sub.id) for sub in subscriptions]

    async def delete_subscription(self, subscription_id: str) -> WebhookOperationResult:
        try:
            async with httpx.AsyncClient() as client:
                response = await client.delete(f"{_API_URL}/subscriptions/{subscription_id}", timeout=30.0)
                response.raise_for_status()
        except httpx.HTTPError as e:
            return WebhookOperationResult(
                subscription_id=subscription_id,
                status=WebhookSubscriptionStatus.ERROR,
                error=str(e),
            )
        return WebhookOperationResult(subscription_id=subscription_id, status=WebhookSubscriptionStatus.DELETED)
```

The task counts the statuses it gets back, so each outcome has to be distinguishable:

| Outcome | Return | What `reconcile_provider_webhooks` does |
| - | - | - |
| Subscriptions deleted | one `DELETED` result each | Logs `deleted=N, errors=0` and succeeds |
| Provider confirms none registered | `[]` | Logs `deleted=0, errors=0` and succeeds |
| A delete is rejected | an `ERROR` result for it | Raises, so the task retries; the next attempt lists again |
| The *listing* fails | let the exception propagate | Retries |

> [!WARNING]
>
> Never turn a failed lookup into `[]`. A helper that swallows HTTP errors and returns `None` or an empty list makes an outage indistinguishable from "nothing is registered", and the task then reports success while live subscriptions keep delivering. Where the provider addresses a subscription by an id you chose, skip the listing entirely: `google_health` deletes its stable `open-wearables` subscriber directly and reports a `404` as `skipped`, so absence and failure can never be confused.

> [!NOTE]
>
> If `webhook_registration_api=False` (the default), switching sync mode to `webhook` only updates the database — you must register subscriptions manually in the provider's developer portal pointing to `{API_BASE_URL}/api/v1/providers/{provider}/webhooks`.

#### Per-user subscriptions

Some providers create subscriptions with each user's own bearer token rather than one app-level registration (Withings). For those, also set `webhook_subscription_per_user=True` and:

1. Make `register_subscriptions(callback_url)` and `deregister_subscriptions()` dispatch one per-connection task each (`UserConnectionRepository.get_all_active_by_provider`) instead of subscribing anything themselves, and return no results — nothing is subscribed or deleted there. The `callback_url` argument is unused; each per-connection task builds its own.
2. Add that task under `app/integrations/celery/tasks/<provider>/`, next to `garmin/`. It stays provider-scoped rather than shared, so it can call your own service directly instead of forcing a per-user method onto `BaseWebhookService`. Give it a single `user_id` argument and have it work against the provider's currently configured live-sync mode (`ProviderSettingsRepository.get_live_sync_mode`), listing the provider's existing subscriptions first and changing only the gap, so a redelivered task is safe and a mode of `pull` revokes rather than creates.
3. Drive both ends from `BaseOAuthTemplate` rather than adding new hooks. Override `_save_connection` to enqueue that task after calling `super()` — the connection and its token are committed by then — and `deregister_user` to revoke, which disconnect, data purge and account deletion all already call while the connection is still active.

Each result entry's `status` drives the task's retry policy: `error` retries with the failures attached, anything else counts as success. Return `skipped` for what retrying cannot fix, such as an unusable callback URL or a revoked grant.

Because each connection holds its own subscription, both `register_subscriptions()` and `deregister_subscriptions()` fan out the same way — the per-connection task reads the configured mode and revokes when it is `pull`, so neither direction is special-cased in shared code. `app/services/providers/withings/webhook_service.py` and `app/integrations/celery/tasks/withings/notify_sync_task.py` are the reference implementation.

***

## Troubleshooting

> [accordion] Data not normalizing correctly
>
> Add detailed logging in `_normalize_workout` to inspect raw data structure. Compare against provider's API documentation.

> [accordion] Duplicate workouts being created
>
> Implement duplicate detection in `_save_workout` based on `provider_id`. Check if workout with same `provider_id` already exists.

> [accordion] Missing workout types
>
> Add missing types to your mapping file. Consider adding a fallback type ("other") and logging unmapped types for future updates.

***

## Summary Checklist

Use this checklist to ensure you've completed all steps:

* [ ] Created provider directory structure (`strategy.py`, `oauth.py`, `workouts.py`)
* [ ] Implemented `ProviderStrategy` with required properties and **`capabilities`** declaration
* [ ] Implemented `ProviderOAuth` with endpoints, credentials, and user info fetch
* [ ] Implemented `ProviderWorkouts` with normalization logic
* [ ] Implemented `ProviderWebhookHandler` extending `BaseWebhookHandler` (if `webhook_stream` or `webhook_ping`)
* [ ] Wired `self.webhooks` in strategy (or left as `None` if no webhooks)
* [ ] Created workout type mapping file
* [ ] Registered provider in `ProviderFactory`
* [ ] Added provider to `ProviderName` enum
* [ ] Added provider icon to static assets
* [ ] Added environment variables to `.env` and `config.py`
* [ ] Tested OAuth flow end-to-end
* [ ] Tested data synchronization
* [ ] Verified data in database
* [ ] Tested webhook delivery at `POST /api/v1/providers/{provider}/webhooks` (if applicable)
* [ ] Tested subscription verification at `GET /api/v1/providers/{provider}/webhooks` (if applicable)
* [ ] If `webhook_registration_api=True`: implemented `register_subscriptions()` and `deregister_subscriptions()` on the webhook service, and verified both fire on the sync mode switch
* [ ] If `webhook_subscription_per_user=True`: implemented the per-connection reconcile on your webhook service plus its provider-scoped task, overrode `_save_connection` and `deregister_user`, and verified the fan-out reconciles one connection per active link in both directions
* [ ] Added error handling and logging
* [ ] Updated API documentation

> [!TIP]
>
> Congratulations! You've successfully integrated a new provider into OpenWearables. 🎉


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.