The v2 contract
Accept JSON at POST /api/v2/apple/batch. Each batch has a schema_version of 2, a metric, a zero-based batch_index, and total_batches. samples and deletions default to empty arrays and a batch can contain only deletions. source_bundle_id and device are optional. Keep extra fields so you can accept additive changes.
These links are pinned to HealthSave Observatory v1.5.3.
- Batch JSON Schema, including the sample and deletion definitions
- Sample JSON Schema and deletion JSON Schema
- iPhone request headers and OpenAPI snapshot of both API versions
Validate the body version even if X-HealthSave-Schema-Version is missing. The header is advisory. The JSON Schema describes the field types. The reference API notes cover metric-specific rules, including allowed units and which fields each sample type needs.
- Keep the sample’s
uuid, timestamps, source and unit when present. Workouts, sleep and other structured records have their own fields. A single quantity shape cannot represent every sample. - A
day_totalrepresents a local calendar day (localDate). Acomponentis an individual reading. Keep them distinct so you do not count the same activity twice. - For each
deletions[].uuid, mark the matching sample for that user as superseded. Apply the deletions and sample writes together, including when a batch both carries and deletes the same UUID.
Example batch from HealthSave
This iPhone test fixture contains one resting heart rate sample and one deletion. Save the JSON as example.json to try the receivers below.
{
"schema_version": 2,
"metric": "resting_heart_rate",
"batch_index": 0,
"total_batches": 1,
"samples": [
{
"uuid": "D2C70000-0000-4000-8000-000000000003",
"startDate": "2026-08-30T04:00:00.000Z",
"endDate": "2026-08-30T12:31:00.000Z",
"date": "2026-08-30T04:00:00.000Z",
"qty": 49,
"unit": "count/min",
"tzOffsetMinutes": -240,
"source": "Apple Watch"
}
],
"deletions": [
{
"uuid": "D2C70000-0000-4000-8000-00000000007B"
}
],
"source_bundle_id": "com.healthsave.ios",
"device": {
"name": "iPhone",
"model": "iPhone17,2"
}
}
Run a local receiver
Both examples listen on your computer only. They check the body version and append each batch to a JSON Lines file before replying. They return an empty status object and keep deletions in the file for your storage code to apply. Use synthetic test data here.
Python
Save as receiver.py and run python3 receiver.py.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class Receiver(BaseHTTPRequestHandler):
def reply(self, status, body):
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(body).encode())
def do_GET(self):
if self.path == "/api/health":
return self.reply(200, {"status": "ok"})
if self.path == "/api/apple/status":
return self.reply(200, {})
self.reply(404, {})
def do_POST(self):
if self.path != "/api/v2/apple/batch":
return self.reply(404, {})
try:
size = int(self.headers.get("Content-Length", "0"))
if not 0 < size <= 2 * 1024 * 1024:
return self.reply(400, {"error": "Expected up to 2 MiB of JSON"})
batch = json.loads(self.rfile.read(size))
except ValueError:
return self.reply(400, {"error": "Invalid JSON"})
if not isinstance(batch, dict) or batch.get("schema_version") != 2:
return self.reply(422, {"error": "Expected a v2 batch"})
try:
with open("batches-python.jsonl", "a", encoding="utf-8") as log:
log.write(json.dumps(batch) + "\n")
except OSError:
return self.reply(503, {"error": "Could not save batch"})
self.reply(200, {"status": "processed", "wire_schema_version": 2})
HTTPServer(("127.0.0.1", 8000), Receiver).serve_forever()
Node.js
Save as receiver.mjs and run node receiver.mjs.
import { createServer } from "node:http";
import { appendFile } from "node:fs/promises";
createServer(async (req, res) => {
const reply = (status, body) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (req.method === "GET" && req.url === "/api/health") {
return reply(200, { status: "ok" });
}
if (req.method === "GET" && req.url === "/api/apple/status") {
return reply(200, {});
}
if (req.method !== "POST" || req.url !== "/api/v2/apple/batch") {
return reply(404, {});
}
const size = Number(req.headers["content-length"]);
if (!Number.isInteger(size) || size <= 0 || size > 2 * 1024 * 1024) {
return reply(400, { error: "Expected up to 2 MiB of JSON" });
}
let batch;
try {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
batch = JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
return reply(400, { error: "Invalid JSON" });
}
if (batch?.schema_version !== 2) {
return reply(422, { error: "Expected a v2 batch" });
}
try {
await appendFile("batches-node.jsonl", JSON.stringify(batch) + "\n");
} catch {
return reply(503, { error: "Could not save batch" });
}
reply(200, { status: "processed", wire_schema_version: 2 });
}).listen(8001, "127.0.0.1");
Send the example
Run this from a second terminal. Use port 8000 for Python or 8001 for Node. A saved batch returns HTTP 200.
curl -i http://127.0.0.1:8000/api/v2/apple/batch -H "Content-Type: application/json" --data-binary @example.json
Connect HealthSave to your receiver
- Serve
GET /api/healthwith{"status":"ok"}. ServeGET /api/apple/statuswith a flat object such as{"resting_heart_rate":{"count":1}}using your stored counts. An empty object works before the first sync. - Validate batches with the schema and the metric rules above. Reply with HTTP
2xxafter the write succeeds. Use400for malformed JSON and422for invalid v2 fields. A temporary storage failure can return503so the app retries. - Handle retries per user using
Idempotency-Keyand a SHA-256 hash of the request bytes. The current iPhone app sendssha256:<hex>as both the key andX-HealthSave-Payload-Hash. Reuse the saved result for the same key and body. Return409if the same key arrives with different bytes. Use the API contract for v1 support and optional sync receipts. - Serve the receiver over HTTPS at an address your iPhone can reach. Require the
x-api-keyheader on write and status routes. In Server Sync, enter the base URL and key. HealthSave appends the route paths.