From 2e0eda92c433d6ca4aa8ea3a8e5d9afbc9f57193 Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 12:50:39 -0700 Subject: [PATCH 1/2] Samples, list defaults, organization paging and batch estimates match the API Co-Authored-By: Claude Opus 5.5 --- saturday/client.py | 33 ++++++++++++++-------- tests/fixtures/contracts.json | 40 +++++++++++++-------------- tests/test_contracts.py | 2 +- tests/test_request_options.py | 52 +++++++++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+), 32 deletions(-) create mode 100644 tests/test_request_options.py diff --git a/saturday/client.py b/saturday/client.py index d421e0f..5709e42 100644 --- a/saturday/client.py +++ b/saturday/client.py @@ -257,9 +257,16 @@ def calculate(self, **request: Any) -> NutritionCalculateResponse: """ return self._client.request("POST", "/v1/nutrition/calculate", json=request) - def batch_calculate(self, scenarios: List[Dict[str, Any]]) -> BatchCalculateResponse: - """Calculate up to 50 sessions. Each scenario counts as one call against your limits.""" - return self._client.request("POST", "/v1/nutrition/calculate/batch", json={"scenarios": scenarios}) + def batch_calculate(self, scenarios: List[Dict[str, Any]], *, estimate_only: bool = False) -> BatchCalculateResponse: + """Calculate up to 50 sessions. Each scenario counts as one call against your limits. + + With ``estimate_only=True`` nothing is calculated or counted: the answer carries only + ``total`` and ``estimated_ms``, the expected wall time of the real call. + """ + body: Dict[str, Any] = {"scenarios": scenarios} + if estimate_only: + body["estimate_only"] = True + return self._client.request("POST", "/v1/nutrition/calculate/batch", json=body) def product_fit(self, **request: Any) -> ProductFitResponse: """Size one catalog product against the athlete's prescription for a session. @@ -297,7 +304,7 @@ def __init__(self, client: Saturday): self._client = client def create(self, **athlete: Any) -> Athlete: - """Create an athlete. At least one of ``name``, ``email`` or ``external_id`` is required. + """Create an athlete. Every field is optional; the answer carries the athlete's ``id``. ``external_id`` is unique within your partner account: one another of your athletes holds creates nothing and raises ``ConflictError`` (``athlete_exists``) whose ``athlete_id`` names @@ -357,8 +364,9 @@ def create_onboarding_link(self, athlete_id: str, locale: Optional[OnboardingLoc return self._client.request("POST", f"/v1/athletes/{_seg(athlete_id)}/onboarding-link", json=body) def batch_create(self, athletes: List[Dict[str, Any]]) -> BatchAthleteResponse: - """Create up to 100 athletes in one call. An item whose ``external_id`` one of your athletes - holds, an earlier item of the same batch included, fails with ``athlete_exists`` and that + """Create up to 100 athletes in one call. Each item needs at least one of ``name``, + ``email`` or ``external_id`` (else ``missing_identifier``). An item whose ``external_id`` one of + your athletes holds, an earlier item of the same batch included, fails with ``athlete_exists`` and that athlete's id in ``errors[i]["athlete_id"]``.""" return self._client.request("POST", "/v1/athletes/batch", json={"athletes": athletes}) @@ -407,7 +415,7 @@ def create(self, athlete_id: str, **activity: Any) -> Activity: def get(self, athlete_id: str, activity_id: str) -> Activity: return self._client.request("GET", f"/v1/athletes/{_seg(athlete_id)}/activities/{_seg(activity_id)}") - def list(self, athlete_id: str, *, limit: int = 20, cursor: Optional[str] = None) -> ActivityListResponse: + def list(self, athlete_id: str, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> ActivityListResponse: """One page of the athlete's activities. Pass ``pagination["next_cursor"]`` back as ``cursor``.""" return self._client.request( "GET", f"/v1/athletes/{_seg(athlete_id)}/activities", params=_params(limit=limit, cursor=cursor) @@ -598,8 +606,10 @@ def create(self, display_name: str, *, description: Optional[str] = None, sport: body = {k: v for k, v in {"display_name": display_name, "description": description, "sport": sport}.items() if v is not None} return self._client.request("POST", "/v1/organizations", json=body) - def list(self) -> OrganizationListResponse: - return self._client.request("GET", "/v1/organizations") + def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> OrganizationListResponse: + """One page of organizations, newest first: ``limit`` 1 to 200 (default 50). Pass + ``pagination["next_cursor"]`` back as ``cursor``.""" + return self._client.request("GET", "/v1/organizations", params=_params(limit=limit, cursor=cursor)) def get(self, org_id: str) -> Organization: return self._client.request("GET", f"/v1/organizations/{_seg(org_id)}") @@ -918,8 +928,9 @@ def list_webhooks(self) -> Dict[str, Any]: def register_webhook(self, url: str, *, events: Optional[List[str]] = None) -> Dict[str, Any]: """Register a webhook endpoint. The signing secret is returned ONCE — store it. - ``events`` subscribes to a subset of ``concern.detected`` / - ``athlete.needs_attention``; omit (or pass empty) for all coach events. + Omit ``events`` (or pass empty) for ``concern.detected`` and ``athlete.needs_attention``; + ``["*"]`` subscribes to every coach event, ``coach.message.sent`` and ``athlete.deleted`` + included. """ return self._client.request( "POST", "/v1/coach/webhooks", json={"url": url, "events": events or []} diff --git a/tests/fixtures/contracts.json b/tests/fixtures/contracts.json index 8d9e779..0ace389 100644 --- a/tests/fixtures/contracts.json +++ b/tests/fixtures/contracts.json @@ -1,6 +1,6 @@ { "_meta": { - "backend_sha": "c5382f6d157b4d8074719e25c033adf95887d3b1", + "backend_sha": "5ff56d7cfc79610f728473c77a1aa8bda8c33818", "source": "pkg/api Go JSON types, stored-prescription/list/settings HTTP handlers, the coach billing structs in pkg/purchase, pkg/connect and pkg/coachbilling, and the profile-sharing types in pkg/api, pkg/partner and pkg/webhook; synthetic values, no API calls" }, "activity": { @@ -61,7 +61,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true } }, "activity_full_banded": { @@ -85,7 +85,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "precision": { "profile_complete": false, @@ -123,7 +123,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "subscription_cta": { "message": "Subscribe", @@ -150,7 +150,7 @@ "message": "Complete your profile" } }, - "trial_ends_at": 1700000500000, + "trial_ends_at": 1700000500, "trial_cap_reached": true, "trial_cap_note": "Daily cap reached" }, @@ -177,10 +177,10 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "tier_source": "trial", - "trial_ends_at": 1700000500000, + "trial_ends_at": 1700000500, "trial_calls_remaining_today": 0 }, "athlete": { @@ -288,7 +288,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true } }, { @@ -308,7 +308,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "precision": { "profile_complete": false, @@ -692,7 +692,7 @@ "calculations_use": "saturday_app" } }, - "updated_at": 1760000000000 + "updated_at": 1760000000 }, "import_all_failed": { "imported": [], @@ -794,7 +794,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "precision": { "profile_complete": false, @@ -926,7 +926,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "precision": { "profile_complete": false, @@ -964,7 +964,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "precision": { "profile_complete": false, @@ -1000,7 +1000,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true } }, "nutrition_teaser": { @@ -1020,7 +1020,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "subscription_cta": { "message": "Subscribe", @@ -1070,10 +1070,10 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true }, "tier_source": "trial", - "trial_ends_at": 1700000500000, + "trial_ends_at": 1700000500, "trial_calls_remaining_today": 0 }, "nutrition_zero": { @@ -1090,7 +1090,7 @@ "text": "Powered by Saturday", "logo_url": "https://saturday.fit/logo.png", "link": "https://saturday.fit", - "required": false + "required": true } }, "onboarding_link": { @@ -1197,7 +1197,7 @@ "subscription_status": "full", "updated_at": 1700000000 }, - "created_at": 1765467600000 + "created_at": 1765467600 }, "webhook_profile_sharing_changed": { "id": "evt_4f9a2c7e1b8d3a6f0c5e9b2d7a1f4c8e", @@ -1213,6 +1213,6 @@ "subscription_status": "teaser", "updated_at": 1700000000 }, - "created_at": 1765467600000 + "created_at": 1765467600 } } diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 854ff6d..499c6af 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -138,7 +138,7 @@ def test_pagination_and_query_defaults_are_preserved(name, options): def send(request): assert request.method == "GET" assert request.url.path == ("/v1/athletes" if athletes else "/v1/athletes/ath_1/activities") - assert dict(request.url.params) == {key: str(value) for key, value in (options or {"limit": 50 if athletes else 20}).items()} + assert dict(request.url.params) == {key: str(value) for key, value in (options or ({"limit": 50} if athletes else {})).items()} return httpx.Response(200, json=payload) client = Saturday(api_key="sk_test_fixture", max_retries=0) diff --git a/tests/test_request_options.py b/tests/test_request_options.py new file mode 100644 index 0000000..675956e --- /dev/null +++ b/tests/test_request_options.py @@ -0,0 +1,52 @@ +import json + +import httpx + +from saturday import Saturday + + +def _client(send): + client = Saturday(api_key="sk_test_fake", max_retries=0) + client._client.close() + client._client = httpx.Client(base_url=client._base_url, transport=httpx.MockTransport(send)) + return client + + +def test_organizations_list_sends_limit_and_cursor_and_nothing_when_left_out(): + seen = [] + + def send(request): + seen.append(dict(request.url.params)) + return httpx.Response(200, json={"organizations": [], "pagination": {"total": 0, "has_more": False}, "request_id": "req_1"}) + + with _client(send) as client: + client.organizations.list(limit=200, cursor="1700000000") + client.organizations.list() + assert seen == [{"limit": "200", "cursor": "1700000000"}, {}] + + +def test_batch_calculate_sends_estimate_only_only_when_asked(): + bodies = [] + + def send(request): + bodies.append(json.loads(request.content)) + return httpx.Response(200, json={"results": [], "total": 1, "succeeded": 0, "failed": 0, "estimated_ms": 100, "elapsed_ms": 0, "request_id": "req_1"}) + + scenarios = [{"activity_type": "bike", "duration_min": 120}] + with _client(send) as client: + client.nutrition.batch_calculate(scenarios, estimate_only=True) + client.nutrition.batch_calculate(scenarios) + assert bodies == [{"scenarios": scenarios, "estimate_only": True}, {"scenarios": scenarios}] + + +def test_activities_list_leaves_the_page_size_to_the_api(): + seen = [] + + def send(request): + seen.append(dict(request.url.params)) + return httpx.Response(200, json={"activities": [], "pagination": {"total": 0, "has_more": False}, "request_id": "req_1"}) + + with _client(send) as client: + client.activities.list("ath_1") + client.activities.list("ath_1", limit=10) + assert seen == [{}, {"limit": "10"}] From 3aebc9b44458c53b4a732835d0a0ee7d149feb7e Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 13:37:39 -0700 Subject: [PATCH 2/2] Error catalog: retryable means retry the same call automatically; false for daily ceilings Co-Authored-By: Claude Opus 5.5 --- saturday/client.py | 2 +- saturday/types.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/saturday/client.py b/saturday/client.py index 5709e42..11f47b4 100644 --- a/saturday/client.py +++ b/saturday/client.py @@ -747,7 +747,7 @@ def discovery(self) -> DiscoveryResponse: return self._client.request("GET", "/v1/") def errors(self) -> ErrorCatalogResponse: - """Every error code the API can return, with its HTTP status and whether a retry can succeed.""" + """Every error code the API can return, with its HTTP status and whether to retry it automatically (``retryable``).""" return self._client.request("GET", "/v1/errors") def health(self) -> HealthResponse: diff --git a/saturday/types.py b/saturday/types.py index 3fa6a7d..8556bba 100644 --- a/saturday/types.py +++ b/saturday/types.py @@ -1176,6 +1176,8 @@ class ErrorCatalogEntry(TypedDict): type: str http_status: int message: str + # Whether a client may retry the same call automatically after Retry-After. False for the daily + # ceilings, which clear only at midnight UTC. retryable: bool documentation_url: str