Skip to content
HealthSave Get the app

HealthSave data format v2

Build a receiver for Apple Health batches sent by HealthSave. Use the versioned JSON schemas, an iPhone test fixture, and minimal Python and Node.js receivers.

By HealthSave · Updated

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.

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_total represents a local calendar day (localDate). A component is 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

  1. Serve GET /api/health with {"status":"ok"}. Serve GET /api/apple/status with a flat object such as {"resting_heart_rate":{"count":1}} using your stored counts. An empty object works before the first sync.
  2. Validate batches with the schema and the metric rules above. Reply with HTTP 2xx after the write succeeds. Use 400 for malformed JSON and 422 for invalid v2 fields. A temporary storage failure can return 503 so the app retries.
  3. Handle retries per user using Idempotency-Key and a SHA-256 hash of the request bytes. The current iPhone app sends sha256:<hex> as both the key and X-HealthSave-Payload-Hash. Reuse the saved result for the same key and body. Return 409 if the same key arrives with different bytes. Use the API contract for v1 support and optional sync receipts.
  4. Serve the receiver over HTTPS at an address your iPhone can reach. Require the x-api-key header on write and status routes. In Server Sync, enter the base URL and key. HealthSave appends the route paths.

Get HealthSave on the App Store · See compatible servers