From 21542fa3e760fac654aace6edf61bdeb30d172a9 Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 10:40:44 -0700 Subject: [PATCH 1/3] Fix code examples and docs mismatches against the SDKs Guard optional precision and Retry-After, add status checks and batch error handling, store rotated OAuth tokens, correct error catalog details, and align response examples with the SDK types and fixtures. --- authentication.mdx | 4 +-- error-handling.mdx | 12 ++++---- guides/activities.mdx | 6 ++++ guides/athletes.mdx | 18 ++++++++---- guides/attribution.mdx | 2 +- guides/batch-operations.mdx | 32 ++++++++++++++++++++ guides/data-policy.mdx | 2 +- guides/feature-gates.mdx | 2 +- guides/freemium-model.mdx | 32 ++++++++++---------- guides/fueling-profile.mdx | 1 + guides/nutrition-calculation.mdx | 19 ++++++++++-- guides/oauth2.mdx | 20 +++++++++---- guides/organizations.mdx | 3 ++ guides/prep-and-products.mdx | 2 ++ guides/webhooks.mdx | 50 ++++++++++++++++++++++++-------- quickstart.mdx | 22 ++++++++++++-- rate-limiting.mdx | 21 +++++++++----- 17 files changed, 186 insertions(+), 62 deletions(-) diff --git a/authentication.mdx b/authentication.mdx index 222179e..29fc622 100644 --- a/authentication.mdx +++ b/authentication.mdx @@ -59,7 +59,7 @@ import os import requests headers = {"Authorization": f"Bearer {os.environ['SATURDAY_API_KEY']}"} -response = requests.get("https://api.saturday.fit/v1/athletes", headers=headers) +response = requests.get("https://api.saturday.fit/v1/athletes", headers=headers, timeout=30) ``` ```typescript TypeScript @@ -155,6 +155,6 @@ Authentication and authorization failures share the standard [error envelope](/e | `plan_inactive` | `authorization_error` | 403 | The key comes with a paid Saturday plan, and the plan on its account has ended. It works again, with its athletes as they were, once the plan is active | | `insufficient_scope` | `authorization_error` | 403 | The key's scopes don't permit this method | | `coach_tier_required` | `authorization_error` | 403 | A `cp_` key whose coach is below Pro Coach | -| `internal_error` | `api_error` | 503 | Key verification is temporarily unavailable. Retry rather than rotating a working key | +| `service_unavailable` | `api_error` | 503 | Key verification is temporarily unavailable. Retry rather than rotating a working key | A key used against the wrong environment fails closed as `invalid_api_key`, and the message names the environment the key was issued for. Each environment keeps separate key records, and a record whose environment is not the host's is refused even if it is present. diff --git a/error-handling.mdx b/error-handling.mdx index 4a26aec..a75efa5 100644 --- a/error-handling.mdx +++ b/error-handling.mdx @@ -73,7 +73,7 @@ Branch on `type` for handling class, and on `code` for the specific case. A type | `api_error` | 500, 502, 503 | Saturday-side failure (500), upstream service (502), transient dependency (503) | - A 404 carries one of two types. `not_found_error` means the URL itself found no endpoint (including endpoints not available to your key), always with `code: "resource_not_found"`. `resource_not_found` as a type comes from an endpoint that could not find the thing you referenced, and its `code` narrows it: `athlete_not_found`, `activity_not_found`, `prescription_not_found`, `key_not_found`, `webhook_not_found`, `integration_not_found` (a disconnect for a provider the athlete never connected). Handle both types as the same case unless you need the distinction. A 429 carries `type: "rate_limit_error"`, and its `code` says which limit was reached ([Rate Limiting](/rate-limiting)). Switching on `type` means using the values in the table above. + A 404 carries one of two types. `not_found_error` means the URL itself found no endpoint (including endpoints not available to your key), always with `code: "resource_not_found"`. `resource_not_found` as a type comes from an endpoint that could not find the thing you referenced, and its `code` narrows it: `athlete_not_found`, `activity_not_found`, `prescription_not_found`, `key_not_found`, `webhook_not_found`, `integration_not_found` (a disconnect for a provider the athlete never connected). Handle both types as the same case unless you need the distinction. The catalog also lists `code: "not_found"` for an endpoint that is not available in this environment, so treat that code as the same case too. A 429 carries `type: "rate_limit_error"`, and its `code` says which limit was reached ([Rate Limiting](/rate-limiting)). Switching on `type` means using the values in the table above. Safety ceilings do not surface as an error status. A prescription that runs into a guardrail returns `200` with the clamped values plus `safety.warnings` and `safety.requires_human_review` set. See [Safety](/guides/safety). @@ -109,8 +109,9 @@ def request_with_retry(make_request, max_retries=3): return response if response.status_code == 429: - wait = int(response.headers["Retry-After"]) - if response.json()["error"]["code"] in RETRY_429 and wait <= 30: + raw = response.headers.get("Retry-After") + wait = int(raw) if raw and raw.isdigit() else None + if wait is not None and response.json()["error"]["code"] in RETRY_429 and wait <= 30: time.sleep(wait) continue return response @@ -135,9 +136,10 @@ async function requestWithRetry( if (attempt === maxRetries) return response; if (response.status === 429) { - const wait = Number(response.headers.get("Retry-After")); + const header = response.headers.get("Retry-After"); + const wait = header === null ? undefined : Number(header); const { error } = await response.clone().json(); - if (!RETRY_429.has(error.code) || wait > 30) return response; + if (!RETRY_429.has(error.code) || wait === undefined || wait > 30) return response; await new Promise((r) => setTimeout(r, wait * 1000)); continue; } diff --git a/guides/activities.mdx b/guides/activities.mdx index 1d5376d..cc3565a 100644 --- a/guides/activities.mdx +++ b/guides/activities.mdx @@ -33,8 +33,11 @@ response = requests.post( "duration_min": 120, "intensity_level": 5, "thermal_stress_level": 4, + "is_race_event": False, + "meal_before_min": 120, "external_id": "your-activity-88213", }, + timeout=30, ) activity = response.json() @@ -55,6 +58,8 @@ const response = await fetch( duration_min: 120, intensity_level: 5, thermal_stress_level: 4, + is_race_event: false, + meal_before_min: 120, external_id: "your-activity-88213", }), } @@ -241,6 +246,7 @@ response = requests.post( "rating": 4, "notes": "Felt good until mile 18, then energy dropped", }, + timeout=30, ) ``` diff --git a/guides/athletes.mdx b/guides/athletes.mdx index 98bfa7f..9273a5e 100644 --- a/guides/athletes.mdx +++ b/guides/athletes.mdx @@ -31,9 +31,12 @@ response = requests.post( "weight_kg": 70, "settings": {"sweat_level": 7, "saltiness": 5}, }, + timeout=30, ) athlete = response.json() +if response.status_code >= 400: + raise RuntimeError(athlete["error"]) print(f"Saturday ID: {athlete['id']}") ``` @@ -56,6 +59,7 @@ const response = await fetch("https://api.saturday.fit/v1/athletes", { }); const athlete = await response.json(); +if (!response.ok) throw new Error(athlete.error.message); console.log(`Saturday ID: ${athlete.id}`); ``` @@ -66,7 +70,8 @@ console.log(`Saturday ID: ${athlete.id}`); The `external_id` field maps the Saturday athlete to your platform's user. This is your user ID, not Saturday's. Use it to look athletes up without storing Saturday's own IDs: ```bash -GET /v1/athletes?external_id=your-user-12345 +curl "https://api.saturday.fit/v1/athletes?external_id=your-user-12345" \ + -H "Authorization: Bearer $SATURDAY_API_KEY" ``` The answer lists every athlete you created with that `external_id`, newest first, in one page. @@ -75,7 +80,7 @@ An `external_id` belongs to one athlete in your account. A create with an `exter ## Profile fields -Every field is optional at create time. The athlete's fueling profile is what makes prescriptions exact, so the fields below split into two groups: the ones the engine needs before it will return exact numbers, and the ones that narrow the band further. An athlete missing any safety-core field gets a range instead of a number. See [Athlete Onboarding](/guides/onboarding). +Send at least one of `name`, `email` or `external_id` at create time; every other field is optional. The athlete's fueling profile is what makes prescriptions exact, so the fields below split into two groups: the ones the engine needs before it will return exact numbers, and the ones that narrow the band further. An athlete missing any safety-core field gets a range instead of a number. See [Athlete Onboarding](/guides/onboarding). ### Top-level fields @@ -95,7 +100,7 @@ Saturday sets `id`, `partner_id`, `created_at`, `updated_at`, `profile_complete` ### Settings: the fueling profile -`settings` holds the fields the engine reads. The 1-9 scales are odd-point selectors, not continuous sliders: send 1, 3, 5, 7, or 9. +`settings` holds the fields the engine reads. The 1-9 scales take any whole number from 1 to 9. | Field | Type | Values | Safety-core | |-------|------|--------|-------------| @@ -160,6 +165,7 @@ response = requests.patch( "https://api.saturday.fit/v1/athletes/a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d", headers={"Authorization": f"Bearer {os.environ['SATURDAY_API_KEY']}"}, json={"weight_kg": 72, "email": "alex@example.com"}, + timeout=30, ) ``` @@ -200,7 +206,7 @@ Saturday is for athletes 14 and up. On create and on update, a `year_of_birth` t "code": "under_minimum_age", "message": "Saturday is for athletes 14 and up, and year_of_birth 2014 is under that age. Nothing was saved. See https://docs.saturday.fit/guides/athletes", "param": "year_of_birth", - "documentation_url": "https://docs.saturday.fit/errors#under_minimum_age", + "documentation_url": "https://docs.saturday.fit/guides/athletes", "request_id": "req_a1b2c3d4e5f6" } } @@ -238,7 +244,7 @@ Export all data held for an athlete: POST /v1/athletes/{id}/export ``` -Returns JSON containing the athlete's profile, every activity with its prescription and feedback, any conversations with Saturday's assistant, and their consent records. +Returns JSON containing the athlete's profile, every activity with its prescription and feedback, and their consent records. ## Settings schema @@ -248,6 +254,6 @@ Fetch the global settings schema to build dynamic forms: GET /v1/settings/schema ``` -Returns each field's type, valid range or option list, description, and default, so a settings UI does not have to hardcode Saturday's requirements. This is a global schema, identical for every athlete; fetch one athlete's current values with `GET /v1/athletes/{id}/settings`. +Returns each field's type, valid range or option list, description, and default, so a settings UI does not have to hardcode Saturday's requirements. This is a global schema, identical for every athlete; fetch one athlete's current values with `GET /v1/athletes/{id}/settings`. The schema lists the editable fields; a stored settings object can also carry `concerns_answered`, which sending any concern field sets, so keep it when you write a settings object back. For collecting the profile from scratch rather than editing it, `GET /v1/onboarding/questions` returns the same fields as athlete-facing questions with copy, ordering, and answer values. See [Athlete Onboarding](/guides/onboarding). diff --git a/guides/attribution.mdx b/guides/attribution.mdx index 3b9395c..ef2e134 100644 --- a/guides/attribution.mdx +++ b/guides/attribution.mdx @@ -174,7 +174,7 @@ surface.

Hydration: 600-900 mL/hr

Sodium: 300-600 mg/hr

- + Powered by Saturday diff --git a/guides/batch-operations.mdx b/guides/batch-operations.mdx index 057d617..49b1d38 100644 --- a/guides/batch-operations.mdx +++ b/guides/batch-operations.mdx @@ -39,9 +39,12 @@ response = requests.post( "https://api.saturday.fit/v1/nutrition/calculate/batch", headers={"Authorization": f"Bearer {os.environ['SATURDAY_API_KEY']}"}, json={"scenarios": [dict(s, athlete_id=ATHLETE) for s in week]}, + timeout=30, ) data = response.json() +if "error" in data: + raise RuntimeError(data["error"]) errors = {err["index"]: err for err in data.get("errors", [])} results = iter(data["results"]) for i in range(len(week)): @@ -78,6 +81,7 @@ const response = await fetch( ); const data = await response.json(); +if (data.error) throw new Error(data.error.message); const errors = new Map(); for (const error of data.errors ?? []) errors.set(error.index, error); let resultIndex = 0; @@ -107,6 +111,9 @@ Counts and the request ID sit at the top level. Each entry in `results` is the s "carb_g_per_hr": 30, "sodium_mg_per_hr": 300, "fluid_ml_per_hr": 400, + "total_carb_g": 60, + "total_sodium_mg": 600, + "total_fluid_ml": 800, "safety": { "max_safe_fluid_ml_per_hr": 1500, "max_safe_sodium_mg_per_hr": 3000, @@ -114,6 +121,12 @@ Counts and the request ID sit at the top level. Each entry in `results` is the s "requires_human_review": false, "warnings": [], "not_instructions": true + }, + "attribution": { + "text": "Powered by Saturday", + "logo_url": "https://saturday.fit/logo.png", + "link": "https://saturday.fit", + "required": true } }, { @@ -121,6 +134,9 @@ Counts and the request ID sit at the top level. Each entry in `results` is the s "carb_g_per_hr": 55, "sodium_mg_per_hr": 400, "fluid_ml_per_hr": 500, + "total_carb_g": 110, + "total_sodium_mg": 800, + "total_fluid_ml": 1000, "safety": { "max_safe_fluid_ml_per_hr": 1500, "max_safe_sodium_mg_per_hr": 3000, @@ -128,6 +144,12 @@ Counts and the request ID sit at the top level. Each entry in `results` is the s "requires_human_review": false, "warnings": [], "not_instructions": true + }, + "attribution": { + "text": "Powered by Saturday", + "logo_url": "https://saturday.fit/logo.png", + "link": "https://saturday.fit", + "required": true } } ], @@ -198,11 +220,16 @@ response = requests.post( }, ], }, + timeout=30, ) results = response.json() +if "error" in results: + raise RuntimeError(results["error"]) for athlete in results["created"]: print(f"Created: {athlete['name']} -> {athlete['id']}") +for error in results.get("errors", []): + print(f"athlete {error['index']} failed: {error['code']} {error['message']}") ``` ```typescript TypeScript @@ -231,9 +258,13 @@ const response = await fetch("https://api.saturday.fit/v1/athletes/batch", { }); const results = await response.json(); +if (results.error) throw new Error(results.error.message); for (const athlete of results.created) { console.log(`Created: ${athlete.name} -> ${athlete.id}`); } +for (const error of results.errors ?? []) { + console.log(`athlete ${error.index} failed: ${error.code} ${error.message}`); +} ``` @@ -308,6 +339,7 @@ response = requests.post( }, ], }, + timeout=30, ) ``` diff --git a/guides/data-policy.mdx b/guides/data-policy.mdx index 92c9773..ba897ff 100644 --- a/guides/data-policy.mdx +++ b/guides/data-policy.mdx @@ -102,7 +102,7 @@ Saturday provides endpoints for GDPR compliance: | Endpoint | Right | Description | |----------|-------|-------------| -| `POST /v1/athletes/{id}/export` | Data portability | Export the athlete's profile, activities, AI conversations, and consent records as JSON | +| `POST /v1/athletes/{id}/export` | Data portability | Export the athlete's profile, activities, and consent records as JSON | | `POST /v1/athletes/{id}/delete` | Right to erasure | Cascading deletion: revokes the provider connections you supplied, then deletes the athlete and everything stored under them (profile, activities, conversations, consent records, integration tokens) and their link to a Saturday account | | `POST /v1/athletes/{id}/consent`, `GET /v1/athletes/{id}/consent`, `DELETE /v1/athletes/{id}/consent/{consent_id}` | Consent records | Append-only log of consent granted or revoked, by type: `data_processing`, `marketing`, `analytics` | diff --git a/guides/feature-gates.mdx b/guides/feature-gates.mdx index 6e93083..9c3d310 100644 --- a/guides/feature-gates.mdx +++ b/guides/feature-gates.mdx @@ -35,7 +35,7 @@ Alpha features are available to partners who have been invited. Reaching an alph "type": "authorization_error", "code": "feature_alpha", "message": "The products feature is in alpha. Contact api@saturday.fit for early access.", - "documentation_url": "https://docs.saturday.fit/errors#feature_alpha", + "documentation_url": "https://docs.saturday.fit/guides/feature-gates", "request_id": "req_a1b2c3d4e5f6" } } diff --git a/guides/freemium-model.mdx b/guides/freemium-model.mdx index cd1d4c9..ef6ed13 100644 --- a/guides/freemium-model.mdx +++ b/guides/freemium-model.mdx @@ -30,21 +30,22 @@ Partner integrates (free) -> Athletes see teasers (free) -> Athletes subscribe f ## Detecting response type -Both teaser responses and incomplete full-tier profiles carry range fields. Choose the number display from those fields; use `tier` separately to decide whether to show the subscription CTA. Exact zero values may be omitted, so the exact branch defaults them to zero. +Both teaser responses and incomplete full-tier profiles carry range fields. Choose the number display from those fields; use `tier` separately to decide whether to show the subscription CTA. Exact zero values may be omitted, so the exact branch defaults them to zero. An activity calculation nests its exact numbers under `prescription`, so read the number fields from there when it is present. ```python Python data = response.json() +numbers = data.get("prescription", data) -if "carb_range_g_per_hr" in data: - show_range(data["carb_range_g_per_hr"]) - show_range(data["sodium_range_mg_per_hr"]) - show_range(data["fluid_range_ml_per_hr"]) +if "carb_range_g_per_hr" in numbers: + show_range(numbers["carb_range_g_per_hr"]) + show_range(numbers["sodium_range_mg_per_hr"]) + show_range(numbers["fluid_range_ml_per_hr"]) else: - show_exact(data.get("carb_g_per_hr", 0)) - show_exact(data.get("sodium_mg_per_hr", 0)) - show_exact(data.get("fluid_ml_per_hr", 0)) + show_exact(numbers.get("carb_g_per_hr", 0)) + show_exact(numbers.get("sodium_mg_per_hr", 0)) + show_exact(numbers.get("fluid_ml_per_hr", 0)) if data["tier"] == "teaser": show_upgrade_cta(data["subscription_cta"]["subscribe_url"]) @@ -52,15 +53,16 @@ if data["tier"] == "teaser": ```typescript TypeScript const data = await response.json(); +const numbers = data.prescription ?? data; -if (data.carb_range_g_per_hr !== undefined) { - showRange(data.carb_range_g_per_hr); - showRange(data.sodium_range_mg_per_hr); - showRange(data.fluid_range_ml_per_hr); +if (numbers.carb_range_g_per_hr !== undefined) { + showRange(numbers.carb_range_g_per_hr); + showRange(numbers.sodium_range_mg_per_hr); + showRange(numbers.fluid_range_ml_per_hr); } else { - showExact(data.carb_g_per_hr ?? 0); - showExact(data.sodium_mg_per_hr ?? 0); - showExact(data.fluid_ml_per_hr ?? 0); + showExact(numbers.carb_g_per_hr ?? 0); + showExact(numbers.sodium_mg_per_hr ?? 0); + showExact(numbers.fluid_ml_per_hr ?? 0); } if (data.tier === "teaser") { diff --git a/guides/fueling-profile.mdx b/guides/fueling-profile.mdx index 5e5fd0c..c73d817 100644 --- a/guides/fueling-profile.mdx +++ b/guides/fueling-profile.mdx @@ -82,6 +82,7 @@ athlete_id = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" response = requests.get( f"https://api.saturday.fit/v1/athletes/{athlete_id}/fueling-profile", headers={"Authorization": f"Bearer {os.environ['SATURDAY_API_KEY']}"}, + timeout=30, ) response.raise_for_status() body = response.json() diff --git a/guides/nutrition-calculation.mdx b/guides/nutrition-calculation.mdx index 1e34292..d45be87 100644 --- a/guides/nutrition-calculation.mdx +++ b/guides/nutrition-calculation.mdx @@ -35,6 +35,7 @@ response = requests.post( "duration_min": 90, "athlete_weight_kg": 70, }, + timeout=30, ) ``` @@ -119,7 +120,7 @@ The two lists name inputs only and come with a partner API key on every tier, te An `athlete_id` your account does not hold is refused with `404` and code `athlete_not_found`; leave `athlete_id` out for a range estimate. -Profile fields, at the top level of the request, stand in for a stored athlete or override one stored answer for that call: `sex` (`male`, `female` or `intersex`), `age` (years), `athlete_weight_kg` (20 to 250), `sweat_level`, `saltiness`, `satiety_level` and `fitness_level` (1, 3, 5, 7 or 9), `carb_experience` and `usual_carb_consumption` (the values in [Settings: the fueling profile](/guides/athletes#settings-the-fueling-profile)), `carb_upper_limit_override` (50 to 150 g/hr), and `concerns`, one object of the eight flags `performance`, `gut_distress`, `heat_tolerance`, `muscle_cramps`, `faintness`, `hunger`, `thirst` and `drinking_resistance`. +Profile fields, at the top level of the request, stand in for a stored athlete or override one stored answer for that call: `sex` (`male`, `female` or `intersex`), `age` (years), `athlete_weight_kg` (20 to 250), `sweat_level`, `saltiness`, `satiety_level` and `fitness_level` (1 to 9), `carb_experience` and `usual_carb_consumption` (the values in [Settings: the fueling profile](/guides/athletes#settings-the-fueling-profile)), `carb_upper_limit_override` (50 to 150 g/hr), and `concerns`, one object of the eight flags `performance`, `gut_distress`, `heat_tolerance`, `muscle_cramps`, `faintness`, `hunger`, `thirst` and `drinking_resistance`. The request may carry only the fields on this page. Any other field, at any depth, is refused with `400` and code `unsupported_field`, `param` naming it, and the message naming the field it was probably meant to be: `meal_before_mins` answers `Did you mean "meal_before_min"?`. A field spelled the way the athlete or activity request spells it gets that request's spelling: `weight_kg` (send `athlete_weight_kg`), `year_of_birth` (send `age`), `is_race_event` (send `is_race`), `type` (send `activity_type`), `duration` (send `duration_min`) and `settings` (send the profile fields at the top level, or an `athlete_id`). See [Error Handling](/error-handling#a-field-the-request-does-not-take). @@ -267,6 +268,20 @@ An answer with exact numbers carries `legs`: each leg's share, in the order sent {"duration_min": 90, "total_carb_g": 110, "total_sodium_mg": 850, "total_fluid_ml": 1100, "carb_g_per_hr": 73, "sodium_mg_per_hr": 570, "fluid_ml_per_hr": 730}, {"duration_min": 30, "total_carb_g": 30, "total_sodium_mg": 250, "total_fluid_ml": 300, "carb_g_per_hr": 60, "sodium_mg_per_hr": 500, "fluid_ml_per_hr": 600} ], + "safety": { + "max_safe_fluid_ml_per_hr": 1500, + "max_safe_sodium_mg_per_hr": 3000, + "confidence_score": 1, + "requires_human_review": false, + "warnings": [], + "not_instructions": true + }, + "attribution": { + "text": "Powered by Saturday", + "logo_url": "https://saturday.fit/logo.png", + "link": "https://saturday.fit", + "required": true + }, "precision": {"profile_complete": true} } ``` @@ -276,5 +291,5 @@ Each leg's figures are as the app's leg card shows them, per hour as the [per-ho Bricks and triathlons work the same way in [batches](/guides/batch-operations), on [stored activities](/guides/activities#bricks-and-triathlons), in [prep, product fit and compare](/guides/prep-and-products#bricks-and-triathlons), each of which answers leg by leg. Bricks and triathlons are for requests made with a partner API key; an athlete's own assistant connected through the Saturday connector plans single sports. -Every calculation response carries a `precision` object: `profile_complete`, `missing_fields`, and an onboarding invite. Exact numbers require a complete fueling profile; an incomplete one gets a band instead. See [Athlete Onboarding](/guides/onboarding). +Read `precision` when the response carries it: `profile_complete`, `missing_fields`, and an onboarding invite. Exact numbers require a complete fueling profile; an incomplete one gets a band instead. See [Athlete Onboarding](/guides/onboarding). diff --git a/guides/oauth2.mdx b/guides/oauth2.mdx index 9fb261e..9c02aa4 100644 --- a/guides/oauth2.mdx +++ b/guides/oauth2.mdx @@ -148,9 +148,12 @@ response = requests.post( "client_secret": "your_client_secret", "code_verifier": code_verifier, }, + timeout=30, ) tokens = response.json() +if response.status_code >= 400: + raise RuntimeError(tokens["error"]) access_token = tokens["access_token"] # JWT, 1-hour expiry refresh_token = tokens["refresh_token"] # Opaque, 90-day expiry expires_in = tokens["expires_in"] # Seconds until access token expires @@ -171,8 +174,9 @@ const response = await fetch("https://api.saturday.fit/v1/oauth/token", { }); const tokens = await response.json(); -const accessToken = tokens.access_token; // JWT, 1-hour expiry -const refreshToken = tokens.refresh_token; // Opaque, 90-day expiry +if (!response.ok) throw new Error(tokens.error); +let accessToken = tokens.access_token; // JWT, 1-hour expiry +let refreshToken = tokens.refresh_token; // Opaque, 90-day expiry ``` @@ -192,6 +196,8 @@ curl -H "Authorization: Bearer ACCESS_TOKEN_JWT" \ The API scopes requests to the athlete who granted consent. You do not pass an `athlete_id`; it is in the JWT, alongside the partner ID and the granted scopes. +With either SDK, pass the access token as `bearerToken` in TypeScript or `bearer_token` in Python, and it is sent in place of the API key. Both constructors still require an `apiKey` or `api_key` argument. + ## Step 6: Refresh expired tokens Access tokens expire after 1 hour. Use the refresh token to get a new pair: @@ -208,6 +214,7 @@ response = requests.post( "refresh_token": refresh_token, "client_id": "your_partner_id", }, + timeout=30, ) new_tokens = response.json() @@ -229,6 +236,8 @@ const response = await fetch("https://api.saturday.fit/v1/oauth/token", { const newTokens = await response.json(); // Rotation: save the new refresh token, the old one stops working shortly +accessToken = newTokens.access_token; +refreshToken = newTokens.refresh_token; ``` @@ -374,10 +383,9 @@ The subscription-lapse case deserves distinct handling: its description tells th Athletes can revoke access from their Saturday account settings. Partners can revoke programmatically: ```bash -POST /v1/oauth/token/revoke -Content-Type: application/x-www-form-urlencoded - -token=REFRESH_TOKEN +curl -X POST https://api.saturday.fit/v1/oauth/token/revoke \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "token=REFRESH_TOKEN" ``` The endpoint revokes refresh tokens. An access token stays valid until it expires, at most one hour later. Per RFC 7009 this returns `200` whether or not the token existed, so a repeated revoke is not an error. diff --git a/guides/organizations.mdx b/guides/organizations.mdx index c2165a9..083c282 100644 --- a/guides/organizations.mdx +++ b/guides/organizations.mdx @@ -27,6 +27,7 @@ response = requests.post( "description": "Marathon training group", "sport": "run", }, + timeout=30, ) org = response.json() # 201 Created @@ -81,6 +82,7 @@ response = requests.post( "role": "admin", "athlete_id": "a1b2c3d4-...", # optional link to an athlete record }, + timeout=30, ) ``` @@ -196,6 +198,7 @@ response = requests.put( "negotiated_by": "Coach Dana Reyes", "note": "2026 season team agreement", }, + timeout=30, ) ``` diff --git a/guides/prep-and-products.mdx b/guides/prep-and-products.mdx index 3d33fea..f0b3e9f 100644 --- a/guides/prep-and-products.mdx +++ b/guides/prep-and-products.mdx @@ -337,6 +337,8 @@ A plan uses the athlete's exact numbers only when calculate would give them exac | `session_incomplete` | Session inputs, listed in `missing_session_inputs`. Send them in the request (fit, compare) or set them on the activity (prep) | | `profile_and_session_incomplete` | Both lists | | `stored_ranges` | Prep on an activity whose stored prescription is ranges, with nothing missing now (the athlete has answered since): calculate the activity again | +| `trial_allowance` | The athlete's trial has used today's calls or given all its exact answers, or this profile is past the trial's allowance of profiles. `message` says which | +| `simulation_allowance` | Test environment only: the athlete's simulated subscription has given its allowance of exact answers or profiles | A fully onboarded athlete and a session missing `meal_before_min` and `is_race`: diff --git a/guides/webhooks.mdx b/guides/webhooks.mdx index 789528c..506aa48 100644 --- a/guides/webhooks.mdx +++ b/guides/webhooks.mdx @@ -30,9 +30,13 @@ response = requests.post( "athlete.created", ], }, + timeout=30, ) -webhook = response.json()["webhook"] # 201 Created +body = response.json() +if response.status_code >= 400: + raise RuntimeError(body["error"]) +webhook = body["webhook"] # 201 Created # Save webhook["secret"]: you need it to verify signatures print(f"Webhook secret: {webhook['secret']}") ``` @@ -50,7 +54,9 @@ const response = await fetch("https://api.saturday.fit/v1/webhooks", { }), }); -const { webhook } = await response.json(); // 201 Created +const body = await response.json(); +if (!response.ok) throw new Error(body.error.message); +const { webhook } = body; // 201 Created // Save webhook.secret: you need it to verify signatures console.log(`Webhook secret: ${webhook.secret}`); ``` @@ -291,7 +297,10 @@ def handle_webhook(): timestamp = None signature = None for part in parts: + if "=" not in part: + abort(400, "Invalid signature format") key, value = part.split("=", 1) + key = key.strip() if key == "t": timestamp = value elif key == "v1": @@ -301,7 +310,11 @@ def handle_webhook(): abort(400, "Invalid signature format") # 3. Reject stale timestamps (5-minute replay window) - if abs(time.time() - int(timestamp)) > 300: + try: + timestamp_seconds = int(timestamp) + except ValueError: + abort(400, "Invalid signature format") + if abs(time.time() - timestamp_seconds) > 300: abort(400, "Timestamp outside the replay window") # 4. Compute expected signature @@ -344,7 +357,10 @@ app.post( // 2. Parse timestamp and signature const parts = Object.fromEntries( - signatureHeader.split(",").map((p) => p.split("=", 2) as [string, string]) + signatureHeader.split(",").map((p) => { + const eq = p.indexOf("="); + return [p.slice(0, eq).trim(), p.slice(eq + 1)] as [string, string]; + }) ); const timestamp = parts["t"]; const signature = parts["v1"]; @@ -354,7 +370,8 @@ app.post( } // 3. Reject stale timestamps (5-minute replay window) - if (Math.abs(Date.now() / 1000 - parseInt(timestamp)) > 300) { + const timestampSeconds = Number(timestamp); + if (!Number.isFinite(timestampSeconds) || Math.abs(Date.now() / 1000 - timestampSeconds) > 300) { return res.status(400).send("Timestamp too old"); } @@ -367,7 +384,9 @@ app.post( .digest("hex"); // 5. Constant-time comparison - if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) { + const expectedBuffer = Buffer.from(expected); + const signatureBuffer = Buffer.from(signature); + if (expectedBuffer.length !== signatureBuffer.length || !crypto.timingSafeEqual(expectedBuffer, signatureBuffer)) { return res.status(400).send("Invalid signature"); } @@ -408,6 +427,7 @@ Re-enable it from the API once the endpoint is healthy. Re-enabling resets `fail ```bash curl -X PATCH https://api.saturday.fit/v1/webhooks/{webhook_id} \ -H "Authorization: Bearer $SATURDAY_API_KEY" \ + -H "Content-Type: application/json" \ -d '{"active": true}' ``` @@ -422,12 +442,18 @@ curl -X PATCH https://api.saturday.fit/v1/webhooks/{webhook_id} \ ## Managing webhooks ```bash -GET /v1/webhooks # list your webhooks -GET /v1/webhooks/{webhook_id} # read one -PATCH /v1/webhooks/{webhook_id} # change url, events, or active -DELETE /v1/webhooks/{webhook_id} # remove it -POST /v1/webhooks/{webhook_id}/test # send a webhook.test event now -GET /v1/webhooks/{webhook_id}/deliveries # recent delivery attempts +# list your webhooks +curl https://api.saturday.fit/v1/webhooks -H "Authorization: Bearer $SATURDAY_API_KEY" +# read one +curl https://api.saturday.fit/v1/webhooks/{webhook_id} -H "Authorization: Bearer $SATURDAY_API_KEY" +# change url, events, or active +curl -X PATCH https://api.saturday.fit/v1/webhooks/{webhook_id} -H "Authorization: Bearer $SATURDAY_API_KEY" -H "Content-Type: application/json" -d '{"active": false}' +# remove it +curl -X DELETE https://api.saturday.fit/v1/webhooks/{webhook_id} -H "Authorization: Bearer $SATURDAY_API_KEY" +# send a webhook.test event now +curl -X POST https://api.saturday.fit/v1/webhooks/{webhook_id}/test -H "Authorization: Bearer $SATURDAY_API_KEY" +# recent delivery attempts +curl https://api.saturday.fit/v1/webhooks/{webhook_id}/deliveries -H "Authorization: Bearer $SATURDAY_API_KEY" ``` `PATCH /v1/webhooks/{webhook_id}` takes any of `url`, `events`, and `active`, validates a new URL and event list the same way registration does, and returns the updated webhook. A body naming none of the three returns `400` with code `no_changes`. `DELETE` returns `204`. diff --git a/quickstart.mdx b/quickstart.mdx index 2a211ea..990e5ba 100644 --- a/quickstart.mdx +++ b/quickstart.mdx @@ -54,7 +54,22 @@ The response is the stored athlete, with `"profile_complete": true` and an `id`: ```json { "id": "b0bffebc-6575-4689-b97f-4a3bbf9cd364", + "partner_id": "your-partner-id", "external_id": "user-42", + "sex": "female", + "year_of_birth": 1990, + "weight_kg": 62, + "settings": { + "sweat_level": 5, + "saltiness": 5, + "satiety_level": 5, + "fitness_level": 5, + "carb_experience": "range_40_60", + "usual_carb_consumption": "range_60_80", + "concerns_answered": true + }, + "created_at": 1797584400, + "updated_at": 1797584400, "profile_complete": true } ``` @@ -118,7 +133,7 @@ curl -X POST https://api.saturday.fit/v1/nutrition/calculate \ |-------|---------------| | `carb_g_per_hr`, `sodium_mg_per_hr`, `fluid_ml_per_hr` | Per-hour targets, whole numbers, as the Saturday app shows them | | `total_*` | Totals for the whole session | -| `precision.profile_complete` | `true`: these are exact numbers. `false`: the response carries ranges instead (step 5) | +| `precision.profile_complete` | When `precision` is present, `true`: these are exact numbers. `false`: the response carries ranges instead (step 5) | | `tier`, `tier_source` | `full` with `trial`: the athlete's 14-day trial gives exact numbers. It started with this call: 15 calls on the first day, then 5 a day, up to 42 in all | | `safety` | Shown on every response. Show each warning to the athlete. `not_instructions` marks the numbers as guidance, not commands | | `attribution` | Show it wherever you show the numbers | @@ -166,7 +181,6 @@ An athlete whose profile is missing answers gets ranges and a list of what to as "missing_profile_fields": ["carb_experience"], "message": "For exact numbers, fill in what is missing. This athlete's profile is missing carb_experience: the onboarding link collects it.", "onboarding": { - "url": "https://saturday.fit/onboard?ot=...", "message": "Answer the missing questions once, or have the athlete onboard in the Saturday app, to get exact numbers for this athlete." } }, @@ -176,12 +190,14 @@ An athlete whose profile is missing answers gets ranges and a list of what to as } ``` -`missing_fields` arrives most impactful first. `missing_profile_fields` names the athlete's answers to collect: ask those questions in your app, or send the athlete to `precision.onboarding.url`. A session input your request left out (`meal_before_min`, say) is listed in `missing_fields` too and in `missing_session_inputs`: it is yours to send. Check `precision.profile_complete`, not `tier`, to tell exact numbers from ranges. `trial_ends_at`, like every time the API gives you, is in Unix seconds. +`missing_fields` arrives most impactful first. `missing_profile_fields` names the athlete's answers to collect: ask those questions in your app, or, in the sandbox, send the athlete to `precision.onboarding.url` when the response carries one. A session input your request left out (`meal_before_min`, say) is listed in `missing_fields` too and in `missing_session_inputs`: it is yours to send. Check `precision.profile_complete` when the response carries `precision`, and the range fields when it does not, not `tier`, to tell exact numbers from ranges. `trial_ends_at`, like every time the API gives you, is in Unix seconds. After the trial, an athlete without a Saturday subscription gets `"tier": "teaser"`: ranges and a `subscription_cta` with their subscribe link. See [Freemium Model](/guides/freemium-model) for how the tiers are decided and how the subscribe loop pays you. ## 6. Use an SDK +The TypeScript snippets in these guides use top-level `await`, so run them as ES modules: save them with an `.mts` extension, or set `"type": "module"` in your `package.json`. + ```bash TypeScript diff --git a/rate-limiting.mdx b/rate-limiting.mdx index 4e04c90..0bf5aec 100644 --- a/rate-limiting.mdx +++ b/rate-limiting.mdx @@ -47,7 +47,7 @@ Exceeding a limit returns `429 Too Many Requests`: "type": "rate_limit_error", "code": "rate_limit_exceeded", "message": "Rate limit exceeded. Retry after 1 seconds.", - "documentation_url": "https://docs.saturday.fit/errors#rate_limit_exceeded", + "documentation_url": "https://docs.saturday.fit/rate-limiting", "request_id": "req_abc123def456" } } @@ -87,11 +87,12 @@ response = make_api_request() if response.status_code == 429: code = response.json()["error"]["code"] - wait = int(response.headers["Retry-After"]) - if code == "rate_limit_exceeded" or (code == "catalog_paced" and wait <= 30): + raw = response.headers.get("Retry-After") + wait = int(raw) if raw and raw.isdigit() else None + if wait is not None and (code == "rate_limit_exceeded" or (code == "catalog_paced" and wait <= 30)): time.sleep(wait) response = make_api_request() - elif code in DAILY: + elif code in DAILY and wait is not None: schedule_after_reset(wait) # resumes after midnight UTC ``` @@ -108,11 +109,12 @@ let response = await makeApiRequest(); if (response.status === 429) { const { error } = await response.json(); - const wait = Number(response.headers.get("Retry-After")); - if (error.code === "rate_limit_exceeded" || (error.code === "catalog_paced" && wait <= 30)) { + const header = response.headers.get("Retry-After"); + const wait = header === null ? undefined : Number(header); + if (wait !== undefined && (error.code === "rate_limit_exceeded" || (error.code === "catalog_paced" && wait <= 30))) { await new Promise((r) => setTimeout(r, wait * 1000)); response = await makeApiRequest(); - } else if (DAILY.has(error.code)) { + } else if (DAILY.has(error.code) && wait !== undefined) { scheduleAfterReset(wait); // resumes after midnight UTC } } @@ -159,7 +161,10 @@ A prescription for the same inputs is stable. Cache the result and recalculate w ### Use the batch endpoint ```bash -POST /v1/nutrition/calculate/batch +curl -X POST https://api.saturday.fit/v1/nutrition/calculate/batch \ + -H "Authorization: Bearer $SATURDAY_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"scenarios": [{"activity_type": "run", "duration_min": 45}]}' ``` Each item in a batch debits a token, so a batch of 10 costs what 10 calls cost. What it saves is round trips, not quota. See [Batch Operations](/guides/batch-operations). From ed055495de52730b5e75fc6799969dee5bd6710b Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 10:44:15 -0700 Subject: [PATCH 2/3] Review fixes: keep odd-point scales; daily 429 scheduling without a Retry-After The settings-scale wording goes back to "1, 3, 5, 7 or 9": PR #98 sets those values on purpose. A daily ceiling with no Retry-After header (older API) still schedules after midnight UTC, as saturday-node's RateLimitError treats it. Co-Authored-By: Claude Opus 5.5 --- guides/athletes.mdx | 2 +- guides/nutrition-calculation.mdx | 2 +- rate-limiting.mdx | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/guides/athletes.mdx b/guides/athletes.mdx index 9273a5e..13f2dc2 100644 --- a/guides/athletes.mdx +++ b/guides/athletes.mdx @@ -100,7 +100,7 @@ Saturday sets `id`, `partner_id`, `created_at`, `updated_at`, `profile_complete` ### Settings: the fueling profile -`settings` holds the fields the engine reads. The 1-9 scales take any whole number from 1 to 9. +`settings` holds the fields the engine reads. The 1-9 scales are odd-point selectors, not continuous sliders: send 1, 3, 5, 7, or 9. | Field | Type | Values | Safety-core | |-------|------|--------|-------------| diff --git a/guides/nutrition-calculation.mdx b/guides/nutrition-calculation.mdx index d45be87..c24e98f 100644 --- a/guides/nutrition-calculation.mdx +++ b/guides/nutrition-calculation.mdx @@ -120,7 +120,7 @@ The two lists name inputs only and come with a partner API key on every tier, te An `athlete_id` your account does not hold is refused with `404` and code `athlete_not_found`; leave `athlete_id` out for a range estimate. -Profile fields, at the top level of the request, stand in for a stored athlete or override one stored answer for that call: `sex` (`male`, `female` or `intersex`), `age` (years), `athlete_weight_kg` (20 to 250), `sweat_level`, `saltiness`, `satiety_level` and `fitness_level` (1 to 9), `carb_experience` and `usual_carb_consumption` (the values in [Settings: the fueling profile](/guides/athletes#settings-the-fueling-profile)), `carb_upper_limit_override` (50 to 150 g/hr), and `concerns`, one object of the eight flags `performance`, `gut_distress`, `heat_tolerance`, `muscle_cramps`, `faintness`, `hunger`, `thirst` and `drinking_resistance`. +Profile fields, at the top level of the request, stand in for a stored athlete or override one stored answer for that call: `sex` (`male`, `female` or `intersex`), `age` (years), `athlete_weight_kg` (20 to 250), `sweat_level`, `saltiness`, `satiety_level` and `fitness_level` (1, 3, 5, 7 or 9), `carb_experience` and `usual_carb_consumption` (the values in [Settings: the fueling profile](/guides/athletes#settings-the-fueling-profile)), `carb_upper_limit_override` (50 to 150 g/hr), and `concerns`, one object of the eight flags `performance`, `gut_distress`, `heat_tolerance`, `muscle_cramps`, `faintness`, `hunger`, `thirst` and `drinking_resistance`. The request may carry only the fields on this page. Any other field, at any depth, is refused with `400` and code `unsupported_field`, `param` naming it, and the message naming the field it was probably meant to be: `meal_before_mins` answers `Did you mean "meal_before_min"?`. A field spelled the way the athlete or activity request spells it gets that request's spelling: `weight_kg` (send `athlete_weight_kg`), `year_of_birth` (send `age`), `is_race_event` (send `is_race`), `type` (send `activity_type`), `duration` (send `duration_min`) and `settings` (send the profile fields at the top level, or an `athlete_id`). See [Error Handling](/error-handling#a-field-the-request-does-not-take). diff --git a/rate-limiting.mdx b/rate-limiting.mdx index 0bf5aec..e796d64 100644 --- a/rate-limiting.mdx +++ b/rate-limiting.mdx @@ -92,8 +92,8 @@ if response.status_code == 429: if wait is not None and (code == "rate_limit_exceeded" or (code == "catalog_paced" and wait <= 30)): time.sleep(wait) response = make_api_request() - elif code in DAILY and wait is not None: - schedule_after_reset(wait) # resumes after midnight UTC + elif code in DAILY: + schedule_after_reset(wait) # resumes after midnight UTC; wait is None without a Retry-After header ``` ```typescript TypeScript @@ -114,8 +114,8 @@ if (response.status === 429) { if (wait !== undefined && (error.code === "rate_limit_exceeded" || (error.code === "catalog_paced" && wait <= 30))) { await new Promise((r) => setTimeout(r, wait * 1000)); response = await makeApiRequest(); - } else if (DAILY.has(error.code) && wait !== undefined) { - scheduleAfterReset(wait); // resumes after midnight UTC + } else if (DAILY.has(error.code)) { + scheduleAfterReset(wait); // resumes after midnight UTC; wait is undefined without a Retry-After header } } ``` From 35524f3df1005e9f1e596dc3054a105f58eca273 Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 10:55:16 -0700 Subject: [PATCH 3/3] Review: keep three statements the API's code supports - Single athlete create takes no required field (pkg/api/athletes.go); only a batch item needs one of name, email or external_id (pkg/api/batch.go, missing_identifier). - The export carries conversations when the athlete has any (pkg/api/gdpr.go, gdpr_types.go: conversations, omitted when empty), so both pages name them again. Co-Authored-By: Claude Fable 5.2 --- guides/athletes.mdx | 4 ++-- guides/data-policy.mdx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/guides/athletes.mdx b/guides/athletes.mdx index 13f2dc2..968fe55 100644 --- a/guides/athletes.mdx +++ b/guides/athletes.mdx @@ -80,7 +80,7 @@ An `external_id` belongs to one athlete in your account. A create with an `exter ## Profile fields -Send at least one of `name`, `email` or `external_id` at create time; every other field is optional. The athlete's fueling profile is what makes prescriptions exact, so the fields below split into two groups: the ones the engine needs before it will return exact numbers, and the ones that narrow the band further. An athlete missing any safety-core field gets a range instead of a number. See [Athlete Onboarding](/guides/onboarding). +Every field is optional at create time. A [batch create](/guides/batch-operations) needs at least one of `name`, `email` or `external_id` for each athlete. The athlete's fueling profile is what makes prescriptions exact, so the fields below split into two groups: the ones the engine needs before it will return exact numbers, and the ones that narrow the band further. An athlete missing any safety-core field gets a range instead of a number. See [Athlete Onboarding](/guides/onboarding). ### Top-level fields @@ -244,7 +244,7 @@ Export all data held for an athlete: POST /v1/athletes/{id}/export ``` -Returns JSON containing the athlete's profile, every activity with its prescription and feedback, and their consent records. +Returns JSON containing the athlete's profile, every activity with its prescription and feedback, any conversations with Saturday's assistant, and their consent records. ## Settings schema diff --git a/guides/data-policy.mdx b/guides/data-policy.mdx index ba897ff..92c9773 100644 --- a/guides/data-policy.mdx +++ b/guides/data-policy.mdx @@ -102,7 +102,7 @@ Saturday provides endpoints for GDPR compliance: | Endpoint | Right | Description | |----------|-------|-------------| -| `POST /v1/athletes/{id}/export` | Data portability | Export the athlete's profile, activities, and consent records as JSON | +| `POST /v1/athletes/{id}/export` | Data portability | Export the athlete's profile, activities, AI conversations, and consent records as JSON | | `POST /v1/athletes/{id}/delete` | Right to erasure | Cascading deletion: revokes the provider connections you supplied, then deletes the athlete and everything stored under them (profile, activities, conversations, consent records, integration tokens) and their link to a Saturday account | | `POST /v1/athletes/{id}/consent`, `GET /v1/athletes/{id}/consent`, `DELETE /v1/athletes/{id}/consent/{consent_id}` | Consent records | Append-only log of consent granted or revoked, by type: `data_processing`, `marketing`, `analytics` |