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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

Breaking changes:

- `integrations.sync` takes `"intervals_icu"` only: the API refuses Strava and TrainingPeaks tokens with a `ValidationError` of code `invalid_provider`. Send TrainingPeaks workouts with `activities.import_activities` once the athlete agrees to share them. `sync` takes `date_range` (`{"start", "end"}`; it said `from` and `to`, which the API never read) and `sync_types` (default `["activities"]`, sent for you) as keyword arguments; `refresh_token` and other options are gone (the API did not use them). The answer is `IntegrationSyncResponse`, `{"result", "request_id"}`, with what the sync did under `result` (`IntegrationSyncResult`, whose `status` is `completed`, `partial` or `failed`). `integrations.disconnect` returns `IntegrationDisconnectResponse` (`message`, `provider`, `request_id`), and raises `NotFoundError` (`integration_not_found`) for a provider the athlete never connected. `IntegrationProvider` and `SyncProvider` name the providers each route takes.
- `external_id` is unique within your account. `athletes.create` or `athletes.update` with an `external_id` another of your athletes holds changes nothing and raises the new `ConflictError` (409, code `athlete_exists`), whose `athlete_id` names that athlete; a `batch_create` item fails with `athlete_exists` and `errors[i]["athlete_id"]`. A retried create is safe.
- `meta.discovery()` returns `DiscoveryResponse`: `get_a_key` (`DiscoveryKeyInfo`) says how a key is had (any paid Saturday plan, made at saturday.fit/api, `athletes_per_key`, `api@saturday.fit`). The API no longer sells a key, so nothing in the package names a price or a signup route.
- `products`, `gear` and `ai` are removed, with their types, `AIStreamError` and `AIStreamEvent`. Those routes are not open to partner keys.
- `webhooks.create(url, events)` returns `WebhookCreateResponse`: the webhook, with its signing secret, is under `webhook`; read `response["webhook"]["secret"]`. `webhooks.list()`, `get()`, `update()` and `test()` are typed (`WebhookListResponse`, `Webhook`, `WebhookTestResponse`). The `description` argument is gone; the API does not take one.
- `webhooks.update` takes `url`, `events` and `active` as keyword arguments; `organizations.add_member` takes `role` and `athlete_id` as keyword arguments; `activities.submit_feedback` takes `rating` and `notes`.
Expand All @@ -21,6 +24,12 @@ Breaking changes:

Added:

- `ConflictError` (409); `SaturdayError.athlete_id` and `BatchError["athlete_id"]`.
- The trial's bounds on calculate and the activity calculate (`TrialMetadata`): `trial_start_deferred` (your key has started its new trials for the UTC day), `trial_profile_limit_reached` (the athlete's trial covers its allowance of distinct profiles), `trial_answers_used_up` (the athlete's trial has given all its exact answers) and `trial_note`, words you can show the athlete; on the test environment, `simulated_limit_reached` and `simulation_note`. Product fit and compare answers carry `trial_start_deferred` and `trial_note` on the teaser tier. `PlanBasisSource` gains `trial_allowance` (product fit and compare spend one of the athlete's trial calls, as calculate does, and plan from ranges once today's calls or the trial's exact answers are used) and `simulation_allowance`.
- `PartnerRateLimits` gains `trial_starts_per_day`, `trial_profiles_per_athlete`, `trial_days` (the trial's length) and `trial_answers` (the exact answers one athlete's trial gives in all). `PartnerAccount["plan"]` `individual` is a key that comes with a Saturday account's paid plan.
- `DAILY_LIMIT_CODES` gains `simulated_subscriber_daily_limit_reached`: on the test environment, `testing.simulate_subscription` marks at most 10 athletes per key per UTC day by default, then raises `RateLimitError` with `daily_limit` True and `resets_at`.
- `PermissionDeniedError` documents `plan_inactive` (the paid plan a key comes with has ended; the key works again, with its athletes, once the plan is active) and `resource_limit_exceeded` (the key's athletes are at their limit).
- Documented: `activities.update` with a change to the session removes the stored prescription, so `get_prescription` raises `NotFoundError` (`prescription_not_found`) until the activity is calculated again; `activities.prep` with both `products=` and `legs=` is refused (`invalid_value` on `products`); `athletes.erase` revokes the connections you supplied, deletes everything stored under the athlete and its link to a Saturday account, leaves the member's own Saturday account as it is, and answers 503 `provider_erasure_incomplete`, having deleted nothing, when a connection could not be revoked yet. The README's new "Get a key" section: a key comes with any paid Saturday plan, from saturday.fit/api, and covers 10 athletes; for more, write to api@saturday.fit.
- `nutrition.product_fit`, `nutrition.compare_products` and `activities.prep`, with `PlanBasis` for plans made from the middle of the ranges, naming what is missing.
- Prep, product fit and compare on a brick or triathlon: `product_fit` and `compare_products` take `legs`, and their answers carry `ProductFitLeg` and `ProductCompareLeg` under `legs`, each leg's share with the product or products sized against it; compare's `winner` is `ComparisonWinner`. `activities.prep(..., legs=[...])` takes a product list per leg, and `PrepLeg` comes under `PrepResponse["legs"]`, whose top level is the legs added up.
- `Precision["missing_profile_fields"]` and `Precision["missing_session_inputs"]`: the profile answers and session inputs a calculation lacks, sent to a partner key on every tier. `MissingField["required"]` documents what it marks: the safety core, with every listed field needed for exact numbers.
Expand Down
35 changes: 23 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ pip install saturday

Python 3.9 or later. One dependency: `httpx`.

## Get a key

A key comes with any paid Saturday plan, member or coach: sign in at [saturday.fit/api](https://saturday.fit/api) to make yours. It is shown once and emailed to you. A new key covers 10 athletes; to cover more, write to [api@saturday.fit](mailto:api@saturday.fit) about what you're building. Platform partners get keys with their agreement.

## Quick start

Create an athlete with a complete profile, then calculate a session for them. Use an `sk_test_` key while you build.
Expand Down Expand Up @@ -74,7 +78,7 @@ A calculation carries exact per-hour numbers and totals only when the athlete's
- `precision["missing_session_inputs"]` names the session inputs your call left out. Send every session input on every call: `intensity_level`, `thermal_stress_level`, `meal_before_min` and `is_race`. One left out returns ranges even for a complete profile; `precision["onboarding"]` comes only when profile answers are missing.
- Per-hour figures are whole numbers, as the Saturday app's Fuel card shows them, which is not always the total divided by the session's hours. Totals are for the whole session.
- A zero may be omitted from the response, so read numbers with `.get(field, 0)`.
- A new athlete's first calculation starts a 30-day trial of the full tier: 15 calls on the first day, then 5 a day. `trial_calls_remaining_today` and `trial_ends_at` show where it stands.
- A new athlete's first calculation, product fit or compare starts a trial of the full tier: 15 calls on the first day, then 5 a day, each fit and compare spending one. `trial_calls_remaining_today` and `trial_ends_at` show where it stands, and `client.partner.get()` gives the trial's length in `rate_limits["trial_days"]` and the exact answers it gives in all in `rate_limits["trial_answers"]`. Past a bound the answer is ranges with a flag and a note you can show the athlete: `trial_cap_reached` (today's calls are used), `trial_start_deferred` (your key has started its new trials for the day), `trial_profile_limit_reached` (the trial covers a set number of distinct profiles) or `trial_answers_used_up` (the trial has given all its exact answers), each with `trial_cap_note` or `trial_note`.

## Prep and product fit

Expand Down Expand Up @@ -133,7 +137,9 @@ with Saturday(api_key="sk_test_...") as client:

A stored activity uses `type` and `is_race_event`; a calculation uses `activity_type` and `is_race`. The API refuses the other spelling with a `ValidationError` whose `code` is `unsupported_field`.

When the athlete's profile or the session is missing inputs, prep, product fit and compare plan from the middle of the athlete's ranges and say so in `plan_basis`: its `source` is `profile_incomplete`, `session_incomplete` or both, `missing_profile_fields` and `missing_session_inputs` list what is missing, and `onboarding` comes only when profile answers are. Show `plan_basis["message"]` with the plan. Product answers follow the athlete's Saturday subscription or trial: without one, `tier` is `"teaser"` and the response carries product categories in place of the fit.
When the athlete's profile or the session is missing inputs, prep, product fit and compare plan from the middle of the athlete's ranges and say so in `plan_basis`: its `source` is `profile_incomplete`, `session_incomplete` or both, `missing_profile_fields` and `missing_session_inputs` list what is missing, and `onboarding` comes only when profile answers are. A trial past today's calls or its exact answers plans from ranges too, with `source` `trial_allowance`. Show `plan_basis["message"]` with the plan. Product answers follow the athlete's Saturday subscription or trial: without one, `tier` is `"teaser"` and the response carries product categories in place of the fit.

`activities.update` with a change to the session (`type`, `legs`, `duration_min`, effort, heat, `is_race_event` or `meal_before_min`) removes the stored prescription: `get_prescription` raises `NotFoundError` (`prescription_not_found`) until you calculate the activity again. A field sent at its stored value changes nothing.

## Bricks and triathlons

Expand Down Expand Up @@ -184,7 +190,7 @@ with Saturday(api_key="sk_test_...") as client:
- A leg's sport is `activity_type` on a calculation and `type` on an activity, as for a single session.
- `activities.update` with `legs` replaces them; a brick or triathlon refuses a top-level effort or heat. Changing `type` to a single sport drops the legs.
- Prep, product fit and compare answer `legs` too: each leg's share with the products sized against it, as the Saturday app's Prep page for that leg sizes them. Fit and compare also size the whole session at the top level; prep's top level is its legs added up, each product once. A plan from ranges (`plan_basis`) carries no legs.
- `activities.prep` takes `products=`, sized against each leg with its `servings` counting per leg, or `legs=`, one product list per leg in order. Per-leg lists on a single session, or a count other than the activity's legs, raise a `ValidationError` on `legs`.
- `activities.prep` takes `products=`, sized against each leg with its `servings` counting per leg, or `legs=`, one product list per leg in order, never both (a `ValidationError` on `products`). Per-leg lists on a single session, or a count other than the activity's legs, raise a `ValidationError` on `legs`.
- `client.reference.activity_types()` lists the rules under `linked_session_types`.

## Resources
Expand All @@ -200,7 +206,7 @@ with Saturday(api_key="sk_test_...") as client:
| `client.partner` | `get`, `usage`, `usage_daily`, `list_api_keys`, `create_api_key`, `revoke_api_key`, `rotate_api_key` |
| `client.webhooks` | `create`, `list`, `get`, `update`, `delete`, `test`, `list_deliveries` |
| `client.organizations` | `create`, `list`, `get`, `update`, `add_member`, `list_members`, `remove_member`, `set_offer`, `get_offer`, `delete_offer`, `create_subscription`, `list_subscriptions`, `update_subscription`, `add_licenses`, `list_licenses`, `remove_license` |
| `client.integrations` | `sync`, `status`, `disconnect` |
| `client.integrations` | `sync` (intervals.icu), `status`, `disconnect` |
| `client.testing` | `simulate_subscription` (test keys only) |
| `client.meta` | `discovery`, `errors`, `health` |
| `client.knowledge` | `search`, `list_topics`, `get_article` (early access) |
Expand All @@ -210,20 +216,24 @@ Every method returns the API's JSON as plain dictionaries, typed with the TypedD

Every timestamp a partner key receives is an integer of Unix seconds: on athletes, activities, webhooks and their deliveries, API keys, your account, `trial_ends_at`, the fueling profile's `updated_at`, the export's `exported_at` and every time in its records. Coach routes answer in Unix milliseconds.

`athletes.update_settings` replaces the whole settings object: send every setting you want kept. `athletes.delete` removes the athlete and everything stored under them in your account. `athletes.erase` is for a right-to-erasure request: it also ends the athlete's connected-provider grants, erases what those providers sent, and keeps an audit record of the deletion.
`athletes.update_settings` replaces the whole settings object: send every setting you want kept. `athletes.delete` removes the athlete and everything stored under them in your account. `athletes.erase` is for a right-to-erasure request: it first revokes, at the provider, each connection you supplied for the athlete with `integrations.sync`, then deletes the athlete, everything stored under them and their link to a Saturday account. A linked athlete's own Saturday account is not changed. A 503 with code `provider_erasure_incomplete` means nothing was deleted yet: call `erase` again.

`integrations.sync("intervals_icu", ...)` fetches the activities of the intervals.icu user an access token belongs to, a token your intervals.icu app obtained, and stores them under your athlete; it is the only provider sync takes. Send TrainingPeaks workouts with `activities.import_activities` once the athlete agrees to share them. `integrations.disconnect` ends the connection you supplied and keeps the activities already synced; for a provider the athlete never connected it raises `NotFoundError` (`integration_not_found`).

Nutrition and knowledge sit behind [feature gates](https://docs.saturday.fit/guides/feature-gates) that Saturday opens per partner. Until a gate is open for your key, its routes answer `403` with code `feature_alpha` (`PermissionDeniedError`); ask api@saturday.fit to open one.

## Finding an athlete by your own id
## Your own athlete ids

`athletes.list(external_id=...)` returns the athletes you created with that `external_id`, newest first, in one page. The API does not deduplicate `external_id`, so look an athlete up this way before creating one when a create may have been interrupted.
`external_id` is unique within your account. A create, batch item or update with an `external_id` another of your athletes holds changes nothing and raises `ConflictError` (409, code `athlete_exists`) whose `athlete_id` names that athlete, so a retried create is safe. `athletes.list(external_id=...)` finds the athlete too.

```python
from saturday import Saturday
from saturday import ConflictError, Saturday

with Saturday(api_key="sk_live_...") as client:
found = client.athletes.list(external_id="user-42")["athletes"]
athlete = found[0] if found else client.athletes.create(external_id="user-42", name="Sam")
try:
athlete = client.athletes.create(external_id="user-42", name="Sam")
except ConflictError as error:
athlete = client.athletes.get(error.athlete_id)
print(athlete["id"])
```

Expand Down Expand Up @@ -257,7 +267,7 @@ with Saturday(api_key="cp_live_...") as client:

## Errors, retries and limits

Every API error is a `SaturdayError` with `status`, `code`, `message`, `param`, `request_id` and `error_type`. Subclasses: `ValidationError` (400, with `suggestion` for a field the request does not take), `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RateLimitError` (429).
Every API error is a `SaturdayError` with `status`, `code`, `message`, `param`, `request_id` and `error_type`. Subclasses: `ValidationError` (400, with `suggestion` for a field the request does not take), `AuthenticationError` (401), `PermissionDeniedError` (403: `feature_alpha`; `plan_inactive` when the paid plan a key comes with has ended; `resource_limit_exceeded` when the key's athletes are at their limit), `NotFoundError` (404), `ConflictError` (409, with `athlete_id`), `RateLimitError` (429).

```python
from saturday import RateLimitError, Saturday, ValidationError
Expand Down Expand Up @@ -288,6 +298,7 @@ A `RateLimitError`'s `code` says which limit was hit:
| `intelligence_daily_limit_reached` | Your daily ceiling on calculations, products, inference, knowledge and AI; your athletes, activities and other data keep working | Same |
| `athlete_free_daily_limit_reached` | Your daily budget of calculations sent without an `athlete_id` | Same |
| `distinct_lookup_daily_limit_reached` | Your daily budget of distinct product lookups; repeat lookups keep working | Same |
| `simulated_subscriber_daily_limit_reached` | Test environment: your key has marked its day's athletes with `testing.simulate_subscription`; athletes already marked keep their simulated subscription | Same |

A 5xx is retried after its `Retry-After` (usually 5 seconds) or after 1 s, 2 s and 4 s, up to `max_retries` times, except on a `POST` that creates or changes a record (an athlete, an activity, an import, a webhook), since the server may have done the write; the calculation, product, inference, prep and export `POST`s are retried. The client never sleeps longer than 30 seconds inside one call. `client.partner.get()` shows your limits and `client.partner.usage()` what you have used.

Expand All @@ -307,7 +318,7 @@ client = Saturday(
delegated = Saturday(api_key="sk_live_...", bearer_token="eyJ...")
```

Partner keys start `sk_live_` or `sk_test_`; coach keys start `cp_live_` or `cp_test_`. A test key reaches the test environment, where `client.testing.simulate_subscription(athlete_id)` gives an athlete the full tier. The client holds a connection pool: use it as a context manager or call `close()`.
Partner keys start `sk_live_` or `sk_test_`; coach keys start `cp_live_` or `cp_test_`. A test key reaches the test environment, where `client.testing.simulate_subscription(athlete_id)` gives an athlete the full tier: by default up to 10 athletes a key a UTC day, each with up to 100 exact answers over 3 distinct profiles, then ranges with `simulated_limit_reached`. The client holds a connection pool: use it as a context manager or call `close()`.

## Athlete profile sharing

Expand Down
14 changes: 14 additions & 0 deletions saturday/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
RateLimitError,
ValidationError,
NotFoundError,
ConflictError,
)
from saturday.types import (
Activity,
Expand Down Expand Up @@ -71,6 +72,8 @@
CreatedApiKey,
DailyUsage,
DailyUsageResponse,
DiscoveryKeyInfo,
DiscoveryResponse,
ErrorCatalogEntry,
ErrorCatalogResponse,
FuelingConcerns,
Expand All @@ -90,9 +93,12 @@
HealthResponse,
ImportActivityRequest,
ImportPrescriptionItem,
IntegrationDisconnectResponse,
IntegrationProvider,
IntegrationStatusDetail,
IntegrationStatusResponse,
IntegrationSyncResponse,
IntegrationSyncResult,
LegPrescription,
License,
LicenseListResponse,
Expand Down Expand Up @@ -143,6 +149,7 @@
SimulateSubscriptionResponse,
StoredPrescriptionResponse,
SubscriptionCTA,
SyncProvider,
TrialMetadata,
UsagePeriod,
UsageResponse,
Expand All @@ -168,6 +175,7 @@
"RateLimitError",
"ValidationError",
"NotFoundError",
"ConflictError",
"Activity",
"ActivityFeedback",
"ActivityImportResponse",
Expand Down Expand Up @@ -210,6 +218,8 @@
"CreatedApiKey",
"DailyUsage",
"DailyUsageResponse",
"DiscoveryKeyInfo",
"DiscoveryResponse",
"ErrorCatalogEntry",
"ErrorCatalogResponse",
"FuelingConcerns",
Expand All @@ -229,9 +239,12 @@
"HealthResponse",
"ImportActivityRequest",
"ImportPrescriptionItem",
"IntegrationDisconnectResponse",
"IntegrationProvider",
"IntegrationStatusDetail",
"IntegrationStatusResponse",
"IntegrationSyncResponse",
"IntegrationSyncResult",
"License",
"LicenseListResponse",
"LimitingFactor",
Expand Down Expand Up @@ -276,6 +289,7 @@
"SimulateSubscriptionResponse",
"StoredPrescriptionResponse",
"SubscriptionCTA",
"SyncProvider",
"TrialMetadata",
"UsagePeriod",
"UsageResponse",
Expand Down
Loading