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
35 changes: 23 additions & 12 deletions saturday/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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})

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)}")
Expand Down Expand Up @@ -737,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:
Expand Down Expand Up @@ -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 []}
Expand Down
2 changes: 2 additions & 0 deletions saturday/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
40 changes: 20 additions & 20 deletions tests/fixtures/contracts.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down Expand Up @@ -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": {
Expand All @@ -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,
Expand Down Expand Up @@ -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",
Expand All @@ -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"
},
Expand All @@ -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": {
Expand Down Expand Up @@ -288,7 +288,7 @@
"text": "Powered by Saturday",
"logo_url": "https://saturday.fit/logo.png",
"link": "https://saturday.fit",
"required": false
"required": true
}
},
{
Expand All @@ -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,
Expand Down Expand Up @@ -692,7 +692,7 @@
"calculations_use": "saturday_app"
}
},
"updated_at": 1760000000000
"updated_at": 1760000000
},
"import_all_failed": {
"imported": [],
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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": {
Expand All @@ -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",
Expand Down Expand Up @@ -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": {
Expand All @@ -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": {
Expand Down Expand Up @@ -1197,7 +1197,7 @@
"subscription_status": "full",
"updated_at": 1700000000
},
"created_at": 1765467600000
"created_at": 1765467600
},
"webhook_profile_sharing_changed": {
"id": "evt_4f9a2c7e1b8d3a6f0c5e9b2d7a1f4c8e",
Expand All @@ -1213,6 +1213,6 @@
"subscription_status": "teaser",
"updated_at": 1700000000
},
"created_at": 1765467600000
"created_at": 1765467600
}
}
2 changes: 1 addition & 1 deletion tests/test_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
52 changes: 52 additions & 0 deletions tests/test_request_options.py
Original file line number Diff line number Diff line change
@@ -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"}]