Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
12 changes: 7 additions & 5 deletions error-handling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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) |

<Note>
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.
</Note>

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).
Expand Down Expand Up @@ -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
Expand All @@ -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;
}
Expand Down
6 changes: 6 additions & 0 deletions guides/activities.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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",
}),
}
Expand Down Expand Up @@ -241,6 +246,7 @@ response = requests.post(
"rating": 4,
"notes": "Felt good until mile 18, then energy dropped",
},
timeout=30,
)
```

Expand Down
14 changes: 10 additions & 4 deletions guides/athletes.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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']}")
```

Expand All @@ -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}`);
```

Expand All @@ -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.
Expand All @@ -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).
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

Expand Down Expand Up @@ -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,
)
```

Expand Down Expand Up @@ -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"
}
}
Expand Down Expand Up @@ -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).
2 changes: 1 addition & 1 deletion guides/attribution.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ surface.
<p>Hydration: 600-900 mL/hr</p>
<p>Sodium: 300-600 mg/hr</p>

<a href="https://saturday.fit/subscribe?ref=your_partner_id" class="saturday-attribution">
<a href="https://saturday.fit" class="saturday-attribution">
<img src="https://saturday.fit/brand/powered-by-saturday/powered-by-saturday-stacked-light.svg"
alt="Powered by Saturday" height="40">
</a>
Expand Down
32 changes: 32 additions & 0 deletions guides/batch-operations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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)):
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -107,27 +111,45 @@ 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,
"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
}
},
{
"tier": "full",
"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,
"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
}
}
],
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}`);
}
```

</CodeGroup>
Expand Down Expand Up @@ -308,6 +339,7 @@ response = requests.post(
},
],
},
timeout=30,
)
```

Expand Down
2 changes: 1 addition & 1 deletion guides/feature-gates.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
Expand Down
32 changes: 17 additions & 15 deletions guides/freemium-model.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,37 +30,39 @@ 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.

<CodeGroup>

```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"])
```

```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") {
Expand Down
1 change: 1 addition & 0 deletions guides/fueling-profile.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
17 changes: 16 additions & 1 deletion guides/nutrition-calculation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ response = requests.post(
"duration_min": 90,
"athlete_weight_kg": 70,
},
timeout=30,
)
```

Expand Down Expand Up @@ -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}
}
```
Expand All @@ -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.

<Note>
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).
</Note>
Loading