# Withings API — Complete Reference for AI Agents

> This document contains everything needed to integrate the Withings API.
> It is maintained at https://developer.withings.com/llms.md
> Full interactive documentation: https://developer.withings.com
> API Reference: https://developer.withings.com/api-reference

---

## What is the Withings API?

Withings makes health monitoring devices (smart scales, blood pressure monitors, sleep trackers, activity trackers, thermometers, ECG devices). The Withings API lets partners and developers access health data from these devices on behalf of users who have given consent.

**Base API URL:** `https://wbsapi.withings.net`
**OAuth Authorization URL:** `https://account.withings.com/oauth2_user/authorize2`

---

## Solution Selection

Choose the right solution based on your deployment model:

| Solution | Contract Required | Device Type | Use Case |
|---|---|---|---|
| **Public API** | No | Wi-Fi / BLE | Individual devs, apps like Strava/Lifesum |
| **Cellular Dropship** | Yes | Cellular | Drop-ship pre-configured devices to patients |
| **Cellular Bulkship** | Yes | Cellular | Buy devices in bulk, activate them yourself |
| **SDK (Dropship)** | Yes | Wi-Fi / BLE | Mobile app + drop-ship devices to patients |
| **SDK (Bulkship)** | Yes | Wi-Fi / BLE | Mobile app + buy devices in bulk |
| **Withings RPM** | Yes | All | Healthcare org with existing RPM program |
| **OnSite Mode** | Yes | Wi-Fi / BLE + Body Scan | Clinics, gyms, on-site scanning stations |

### Public API
- OAuth 2.0 web flow (user redirected to Withings login)
- No contract required — create app at https://developer.withings.com/dashboard/
- Scopes: `user.info`, `user.metrics`, `user.activity`, `user.sleepevents`
- Devices: any Wi-Fi or BLE Withings device the user owns

### Cellular Solutions (Dropship / Bulkship)
- Contract required — contact Withings sales
- Devices ship pre-configured with SIM — no phone or Wi-Fi needed
- Data flows directly from device to Withings cloud to your server
- Dropship: Withings ships directly to your patients (logistics API)
- Bulkship: You receive a bulk shipment, activate devices via API

### SDK Solution
- Contract required
- Embed Withings SDK (iOS / Android) into your mobile app
- Users set up devices inside your app (no Withings app needed)
- Available: SDK v2 for iOS (Swift) and Android (Kotlin/Java)
- React Native wrapper also available

### Withings RPM
- Contract required
- For healthcare organizations already using Withings RPM platform
- API access to your organization's patient roster and their data
- List users, get tokens, fetch health data per patient

### OnSite Mode
- Contract required
- Deploy devices in clinics or gyms — activated once, used by many patients
- Body Scan device supported for full body composition scans

---

## Authentication

### OAuth 2.0 Web Flow (Public API and most solutions)

**Step 1: Redirect user to authorization**

```
GET https://account.withings.com/oauth2_user/authorize2
  ?response_type=code
  &client_id=YOUR_CLIENT_ID
  &scope=user.info,user.metrics,user.activity
  &redirect_uri=YOUR_CALLBACK_URL
  &state=RANDOM_CSRF_TOKEN
```

Add `&mode=demo` to test without a real device.

**Step 2: Receive authorization code**

User is redirected to: `https://yourapp.com/callback?code=AUTH_CODE&state=YOUR_STATE`
The code expires in **30 seconds** — exchange immediately.

**Step 3: Exchange code for tokens**

```
POST https://wbsapi.withings.net/v2/oauth2
Content-Type: application/x-www-form-urlencoded

action=requesttoken
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&grant_type=authorization_code
&code=AUTH_CODE
&redirect_uri=YOUR_CALLBACK_URL
```

Response:
```json
{
  "status": 0,
  "body": {
    "userid": "12345",
    "access_token": "a075f8c14fb8df40b08ebc8508533dc332a6910a",
    "refresh_token": "f631236f02342caf8a9c2b26f74e4e24e552e2e0",
    "scope": "user.info,user.metrics,user.activity",
    "expires_in": 10800,
    "token_type": "Bearer"
  }
}
```

Token lifetimes:
- `access_token`: **3 hours** (10800 seconds)
- `refresh_token`: **1 year** (after rotation, the previous token becomes invalid after 8 hours)
- Authorization `code`: **30 seconds**

**Step 4: Refresh access token**

```
POST https://wbsapi.withings.net/v2/oauth2

action=requesttoken
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&grant_type=refresh_token
&refresh_token=YOUR_REFRESH_TOKEN
```

**Important:** Always save the new `refresh_token` from the response — the previous token becomes invalid 8 hours after a new one is issued.

### Request Signing (Contracted Partners)

Some contracted partner endpoints require HMAC-SHA256 request signing.

Signature construction:
1. Sort all POST parameters alphabetically by key (excluding `signature`)
2. Concatenate as: `key=value,key=value,...` (sorted)
3. Sign the string with HMAC-SHA256 using your `client_secret`
4. Encode signature as lowercase hex
5. Add `signature` and `signature_type=hmac_sha256` to your request

---

## API Structure

All API calls use POST with `Content-Type: application/x-www-form-urlencoded`.

**Response envelope:**
```json
{
  "status": 0,
  "body": { ... }
}
```

`status: 0` means success. Any non-zero status is an error.

**Authorization header:** `Authorization: Bearer YOUR_ACCESS_TOKEN`

**Complete OpenAPI 3.0 specification:** https://developer.withings.com/openapi.yaml
Use this spec as the authoritative source for all endpoint parameters, types, and response schemas. The examples below are simplified overviews.

**Pagination:** Some endpoints return paginated results. When a response body contains `more = 1`, additional data is available. Re-call the same endpoint with the `offset` value from the response to fetch the next page. You MUST loop until `more = 0` to retrieve complete data.

---

## Core Endpoints

### Fetch Health Measurements
```
POST https://wbsapi.withings.net/measure
Authorization: Bearer ACCESS_TOKEN

action=getmeas
&startdate=UNIX_TIMESTAMP
&enddate=UNIX_TIMESTAMP
&meastypes=1,4,5,6,8,9,10,11,12,54,71,73,76,77,88,91,123,130,135,136,137,138,139,140
```

Response structure:
```json
{
  "status": 0,
  "body": {
    "updatetime": 1728171131,
    "timezone": "America/New_York",
    "measuregrps": [
      {
        "grpid": 123456789,
        "date": 1728000000,
        "measures": [
          { "value": 7500, "type": 1, "unit": -2 }
        ]
      }
    ]
  }
}
```

Value decoding: `actual_value = value * 10^unit` → `7500 * 10^-2 = 75.00 kg`

### Fetch Activity Data
```
POST https://wbsapi.withings.net/v2/measure
Authorization: Bearer ACCESS_TOKEN

action=getactivity
&startdateymd=2024-01-01
&enddateymd=2024-01-31
&data_fields=steps,distance,elevation,soft,moderate,intense,active,calories,totalcalories,hr_average,hr_min,hr_max,hr_zone_0,hr_zone_1,hr_zone_2,hr_zone_3
```

### Fetch Sleep Data
```
POST https://wbsapi.withings.net/v2/sleep
Authorization: Bearer ACCESS_TOKEN

action=getsummary
&startdateymd=2024-01-01
&enddateymd=2024-01-31
&data_fields=nb_rem_episodes,sleep_score,snoring,snoringepisodecount,sleep_efficiency
```

### List Paired Devices
```
POST https://wbsapi.withings.net/v2/user
Authorization: Bearer ACCESS_TOKEN

action=getdevice
```

---

## Measurement Types Reference

### Scales (Body Composition)
| Type | Measurement | Unit |
|---|---|---|
| 1 | Weight | kg |
| 4 | Height | m |
| 5 | Fat Free Mass | kg |
| 6 | Fat Ratio | % |
| 8 | Fat Mass Weight | kg |
| 9 | Diastolic Blood Pressure | mmHg |
| 10 | Systolic Blood Pressure | mmHg |
| 11 | Heart Rate (pulse) | bpm |
| 12 | Temperature | °C |
| 54 | SpO2 | % |
| 71 | Body Temperature | °C |
| 73 | Skin Temperature | °C |
| 76 | Muscle Mass | kg |
| 77 | Hydration | kg |
| 88 | Bone Mass | kg |
| 91 | Pulse Wave Velocity | m/s |
| 123 | VO2 Max | ml/min/kg |
| 130 | Atrial Fibrillation (QRS) | — |
| 135 | QRS interval | ms |
| 136 | PR interval | ms |
| 137 | QT interval | ms |
| 138 | Corrected QT interval | ms |
| 139 | Atrial Fibrillation from PPG | — |
| 140 | Vascular Age | years |

### Blood Pressure Monitors
Types 9 (diastolic), 10 (systolic), 11 (heart rate)

### Sleep Analyzers / Trackers
Data via sleep API endpoints: sleep score, REM episodes, snoring, heart rate, SpO2, HRV.

### Thermometers
Type 12 (temperature °C)

### BeamO (Multi-metric diagnostic)
Types 9, 10, 11 (BP + HR), 54 (SpO2), 130 (ECG/AFib)

---

## Data Retrieval Patterns

### Pattern 1: Polling (Pull)

Recommended for initial data load and periodic sync.

Use `lastupdate` parameter to fetch only new data since your last sync:
```
POST https://wbsapi.withings.net/measure

action=getmeas
&lastupdate=LAST_SYNC_UNIX_TIMESTAMP
```

Store the `updatetime` from each response and use it as `lastupdate` next time.

### Pattern 2: Webhooks (Notifications)

Recommended for real-time updates. Withings pushes a notification to your server when new data is available, then you fetch the data.

**Subscribe to notifications:**
```
POST https://wbsapi.withings.net/notify
Authorization: Bearer ACCESS_TOKEN

action=subscribe
&callbackurl=https://yourserver.com/withings-webhook
&appli=1
```

`appli` values:
- `1` = Body metrics (weight, fat, etc.)
- `4` = Sleep
- `16` = Blood pressure
- `44` = ECG
- `46` = Activity
- `54` = Afib (PPG)

Note: `appli` notification types are a separate namespace from measurement `type` IDs — `appli=54` (AFib PPG) is unrelated to `meastype=54` (SpO2).

**Notification payload** (Withings POSTs to your callbackurl):
```
userid=12345&startdate=1728000000&enddate=1728171131&appli=1
```

After receiving a notification, fetch the data using the `startdate`/`enddate` from the payload.

**List active subscriptions:**
```
POST https://wbsapi.withings.net/notify
Authorization: Bearer ACCESS_TOKEN

action=list
&appli=1
```

---

## Logistics API (Cellular Solutions)

For Cellular Dropship: create a user order to ship a pre-configured device directly to a patient.

### Create User Order
```
POST https://wbsapi.withings.net/v2/order

action=createuserorder
&client_id=YOUR_CLIENT_ID
&signature=HMAC_SIGNATURE
&nonce=UNIQUE_NONCE
&devicetype=DEVICE_TYPE_ID
&firstname=John
&lastname=Doe
&email=patient@example.com
&address=123 Main St
&city=Boston
&country=US
&zipcode=02101
```

### Observe Order Updates

Subscribe to order status webhooks to track shipping and activation.

---

## Error Codes

| Status | Meaning |
|---|---|
| 0 | Success |
| 100 | Request succeeded but no data found |
| 214 | An error occurred |
| 247 | Invalid userid |
| 250 | The userid is absent, or does not match the client |
| 286 | No such subscription |
| 293 | The callback URL is either absent or incorrect |
| 294 | No notification callback |
| 304 | The authorization code is absent or incorrect |
| 305 | Missing required parameter |
| 342 | OAuth credentials are absent or incorrect |
| 343 | OAuth access token absent or invalid |
| 601 | Too Many Requests — rate limit exceeded |

---

## Rate Limits & Best Practices

- Do not poll more than once every 10 minutes per user
- Use webhook notifications + pull-on-notify architecture for best results
- Store refresh tokens securely — treat them like passwords
- Always save the new refresh token from each refresh response (rotation)
- Use `lastupdate` parameter to avoid re-fetching historical data
- The `updatetime` in each response is your next `lastupdate` value

---

## Recommended Architecture (Notification + Pull)

1. Subscribe to notifications for each user on each `appli` you care about
2. Your server receives a POST webhook from Withings
3. Parse `userid`, `startdate`, `enddate`, `appli` from the webhook
4. Fetch data for that user in that time range
5. Store data in your database
6. Refresh the access token before it expires (every 3 hours) or on 343 error

---

## Quick Links

- Full documentation: https://developer.withings.com
- API Reference: https://developer.withings.com/api-reference
- Developer Dashboard: https://developer.withings.com/dashboard/
- Integration Guides: https://developer.withings.com/developer-guide/v3/withings-solutions/integration-guides
- Available Health Data: https://developer.withings.com/developer-guide/v3/data-api/all-available-health-data
- API Status: https://status.withings.com
- Contact / Sales: https://withingshealthsolutions.com/contact-us-partner-hub/
