Skip to content

Health API reference

Health sleep

FastAPI router for health sleep endpoints.

create_health_sleep

create_health_sleep(request, health_sleep, token_user_id, db, response)

Create health sleep data for a user.

A date that already has a record is answered with a 409; change it with PATCH /{id}.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_sleep HealthSleepCreate

The health sleep data to create, including the date and sleep duration.

required
token_user_id UUID

The ID of the authenticated user extracted from the access token.

required
db Session

Database session dependency for database operations.

required
response Response

The response, whose Location names where the record is read.

required

Returns:

Type Description
HealthSleepRead

health_sleep_schema.HealthSleepRead: The created health sleep data.

Source code in backend/app/modules/health/health_sleep/router.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@router.post(
    "",
    response_model=health_sleep_schema.HealthSleepRead,
    status_code=status.HTTP_201_CREATED,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def create_health_sleep(
    request: Request,
    health_sleep: health_sleep_schema.HealthSleepCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_sleep_schema.HealthSleepRead:
    """Create health sleep data for a user.

    A date that already has a record is answered with a 409; change it with ``PATCH /{id}``.

    Args:
        request: The incoming request, read by the rate limiter.
        health_sleep (health_sleep_schema.HealthSleepCreate): The health sleep data to create,
            including the date and sleep duration.
        token_user_id (uuid.UUID): The ID of the authenticated user extracted from the
            access token.
        db (Session): Database session dependency for database operations.
        response: The response, whose ``Location`` names where the record is read.

    Returns:
        health_sleep_schema.HealthSleepRead: The created health sleep data.

    """
    created = health_sleep_service.create_health_sleep(token_user_id, health_sleep, db)
    core_location.set_location(response, request, "read_health_sleep_by_id", health_sleep_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_health_sleep

delete_health_sleep(request, health_sleep_id, token_user_id, if_match, db)

Delete a health sleep record for the authenticated user.

This endpoint removes a specific health sleep entry from the database for the user identified by the access token. The user must have 'health:write' scope permission.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_sleep_id UUID

The unique identifier of the health sleep record to delete.

required
token_user_id UUID

The user ID extracted from the access token.

required
if_match IfMatch

The If-Match precondition.

required
db Session

Database session dependency for executing the delete operation.

required

Returns:

Name Type Description
None None

This function does not return a value.

Raises:

Type Description
PreconditionFailedError

If the record changed since the client read it.

NotFoundError

If the user has no such record.

Source code in backend/app/modules/health/health_sleep/router.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
@router.delete(
    "/{health_sleep_id}",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_health_sleep(
    request: Request,
    health_sleep_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> None:
    """Delete a health sleep record for the authenticated user.

    This endpoint removes a specific health sleep entry from the database for the user
    identified by the access token. The user must have 'health:write' scope permission.

    Args:
        request: The incoming request, read by the rate limiter.
        health_sleep_id (uuid.UUID): The unique identifier of the health sleep record to delete.
        token_user_id (uuid.UUID): The user ID extracted from the access token.
        if_match: The ``If-Match`` precondition.
        db (Session): Database session dependency for executing the delete operation.

    Returns:
        None: This function does not return a value.

    Raises:
        PreconditionFailedError: If the record changed since the client read it.
        NotFoundError: If the user has no such record.
    """
    # Deletes entry from database
    health_sleep_service.delete_health_sleep(token_user_id, health_sleep_id, db, if_match=if_match)

edit_health_sleep

edit_health_sleep(request, health_sleep_id, health_sleep, token_user_id, db, response, if_match)

Edit health sleep data for a user.

This endpoint updates existing health sleep records in the database for the authenticated user. Requires 'health:write' scope for authorization.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_sleep_id UuidId

ID of the record to change.

required
health_sleep HealthSleepUpdate

The health sleep data to be updated, containing the new values for the health sleep record.

required
token_user_id UUID

The user ID extracted from the JWT access token, used to identify the user making the request.

required
db Session

Database session dependency for performing database operations.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
HealthSleepRead

health_sleep_schema.HealthSleepRead: The updated health sleep record with the new values as stored in the database.

Raises:

Type Description
NotFoundError

If the user has no such record.

PreconditionFailedError

If the record changed since the client read it.

Source code in backend/app/modules/health/health_sleep/router.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
@router.patch(
    "/{health_sleep_id}",
    response_model=health_sleep_schema.HealthSleepRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_health_sleep(
    request: Request,
    health_sleep_id: core_dependencies.UuidId,
    health_sleep: health_sleep_schema.HealthSleepUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> health_sleep_schema.HealthSleepRead:
    """Edit health sleep data for a user.

    This endpoint updates existing health sleep records in the database for the authenticated user.
    Requires 'health:write' scope for authorization.

    Args:
        request: The incoming request, read by the rate limiter.
        health_sleep_id: ID of the record to change.
        health_sleep (health_sleep_schema.HealthSleepUpdate): The health sleep data to be updated,
            containing the new values for the health sleep record.
        token_user_id (uuid.UUID): The user ID extracted from the JWT access token, used to identify
            the user making the request.
        db (Session): Database session dependency for performing database operations.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        health_sleep_schema.HealthSleepRead: The updated health sleep record with the new values
            as stored in the database.

    Raises:
        NotFoundError: If the user has no such record.
        PreconditionFailedError: If the record changed since the client read it.
    """
    updated = health_sleep_service.edit_health_sleep(
        token_user_id, health_sleep_id, health_sleep, db, if_match=if_match
    )
    core_etag.set_etag(response, updated.version)
    return updated

read_health_sleep_all_pagination

read_health_sleep_all_pagination(token_user_id, db, page, date_range, interval=None, has_resting_heart_rate=None)

Retrieve health sleep records for the authenticated user.

One page of records, newest first, optionally limited to an interval and to nights with or without a resting heart rate; the total counts the same records. A record carries has_sleep_stages, not its stages, which are on GET /health/sleep/{health_sleep_id}. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
page ListPage

The requested page and page size.

required
interval Annotated[Interval | None, Query(description='Look back from today over this interval; ignored when `start_date` or `end_date` is given')]

Optional interval looking back from today; ignored when a date range is given.

None
date_range DateRangeQuery

Optional inclusive start and end dates, which replace the interval.

required
has_resting_heart_rate Annotated[bool | None, Query(description='Keep only nights with (`true`) or without (`false`) a resting heart rate')]

Optional filter on whether a night records a resting heart rate.

None

Returns:

Type Description
Page[HealthSleepListItem]

The page of records with the total matching the interval and the filter.

Source code in backend/app/modules/health/health_sleep/router.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@router.get(
    "",
    response_model=core_pagination.Page[health_sleep_schema.HealthSleepListItem],
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_sleep_all_pagination(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    page: core_pagination.ListPage,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval | None,
        Query(description="Look back from today over this interval; ignored when `start_date` or `end_date` is given"),
    ] = None,
    has_resting_heart_rate: Annotated[
        bool | None,
        Query(description="Keep only nights with (`true`) or without (`false`) a resting heart rate"),
    ] = None,
) -> core_pagination.Page[health_sleep_schema.HealthSleepListItem]:
    """Retrieve health sleep records for the authenticated user.

    One page of records, newest first, optionally limited to an interval and to nights with or without a
    resting heart rate; the total counts the same records. A record carries ``has_sleep_stages``, not its
    stages, which are on `GET /health/sleep/{health_sleep_id}`. Access is restricted to users with the
    'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        page: The requested page and page size.
        interval: Optional interval looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates, which replace the interval.
        has_resting_heart_rate: Optional filter on whether a night records a resting heart rate.

    Returns:
        The page of records with the total matching the interval and the filter.
    """
    return health_sleep_service.list_health_sleep(
        token_user_id,
        db,
        page_number=page.page_number,
        num_records=page.num_records,
        interval=interval,
        date_range=date_range,
        has_resting_heart_rate=has_resting_heart_rate,
    )

read_health_sleep_by_id

read_health_sleep_by_id(health_sleep_id, token_user_id, db, response)

Retrieve one of the authenticated user's sleep records; its ETag is the version for If-Match.

Source code in backend/app/modules/health/health_sleep/router.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@router.get(
    "/{health_sleep_id}",
    response_model=health_sleep_schema.HealthSleepRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_sleep_by_id(
    health_sleep_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_sleep_schema.HealthSleepRead:
    """Retrieve one of the authenticated user's sleep records; its ``ETag`` is the version for ``If-Match``."""
    record = health_sleep_service.get_health_sleep(token_user_id, health_sleep_id, db)
    core_etag.set_etag(response, record.version)
    return record

read_health_sleep_chart

read_health_sleep_chart(token_user_id, db, date_range, interval=health_constants.Interval.LAST_7_DAYS)

Chart the authenticated user's total sleep seconds over an interval.

One aggregated point per day, week or month depending on the interval, so the response stays small however long the history. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
interval Annotated[Interval, Query(description='Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given')]

The window to chart, looking back from today; ignored when a date range is given.

LAST_7_DAYS
date_range DateRangeQuery

Optional inclusive start and end dates to chart instead of the interval.

required

Returns:

Type Description
HealthChartSeries

The interval's bucket size and its points, oldest first.

Source code in backend/app/modules/health/health_sleep/router.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@router.get(
    "/chart",
    response_model=health_schema.HealthChartSeries,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_sleep_chart(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval,
        Query(
            description="Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given"
        ),
    ] = health_constants.Interval.LAST_7_DAYS,
) -> health_schema.HealthChartSeries:
    """Chart the authenticated user's total sleep seconds over an interval.

    One aggregated point per day, week or month depending on the interval, so the response stays small
    however long the history. Access is restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        interval: The window to chart, looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates to chart instead of the interval.

    Returns:
        The interval's bucket size and its points, oldest first.
    """
    return health_sleep_service.get_health_sleep_chart(token_user_id, interval, db, date_range=date_range)

read_health_sleep_resting_heart_rate_chart

read_health_sleep_resting_heart_rate_chart(token_user_id, db, date_range, interval=health_constants.Interval.LAST_7_DAYS)

Chart the authenticated user's resting heart rate over an interval.

One aggregated point per day, week or month depending on the interval, so the response stays small however long the history. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
interval Annotated[Interval, Query(description='Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given')]

The window to chart, looking back from today; ignored when a date range is given.

LAST_7_DAYS
date_range DateRangeQuery

Optional inclusive start and end dates to chart instead of the interval.

required

Returns:

Type Description
HealthChartSeries

The interval's bucket size and its points, oldest first.

Source code in backend/app/modules/health/health_sleep/router.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@router.get(
    "/chart/resting-heart-rate",
    response_model=health_schema.HealthChartSeries,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_sleep_resting_heart_rate_chart(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval,
        Query(
            description="Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given"
        ),
    ] = health_constants.Interval.LAST_7_DAYS,
) -> health_schema.HealthChartSeries:
    """Chart the authenticated user's resting heart rate over an interval.

    One aggregated point per day, week or month depending on the interval, so the response stays small
    however long the history. Access is restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        interval: The window to chart, looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates to chart instead of the interval.

    Returns:
        The interval's bucket size and its points, oldest first.
    """
    return health_sleep_service.get_health_sleep_resting_heart_rate_chart(
        token_user_id, interval, db, date_range=date_range
    )

Pydantic request and response shapes for health sleep records.

HRVStatus

Bases: Enum

Enum representing the Heart Rate Variability (HRV) status classification.

Attributes:

Name Type Description
BALANCED

Indicates healthy HRV levels with good cardiovascular autonomic balance.

UNBALANCED

Indicates HRV levels showing some autonomic imbalance or stress.

LOW

Indicates HRV levels that are lower than optimal, suggesting fatigue or overtraining.

POOR

Indicates critically low HRV levels, suggesting significant stress, illness, or recovery issues.

Source code in backend/app/modules/health/health_sleep/schema.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class HRVStatus(Enum):
    """Enum representing the Heart Rate Variability (HRV) status classification.

    Attributes:
        BALANCED: Indicates healthy HRV levels with good cardiovascular autonomic balance.
        UNBALANCED: Indicates HRV levels showing some autonomic imbalance or stress.
        LOW: Indicates HRV levels that are lower than optimal, suggesting fatigue or overtraining.
        POOR: Indicates critically low HRV levels, suggesting significant stress, illness, or recovery issues.
    """

    BALANCED = "BALANCED"
    UNBALANCED = "UNBALANCED"
    LOW = "LOW"
    POOR = "POOR"

HealthSleepBase

Bases: HealthSleepCore

The sleep fields with the sleep stages, the base of every schema that carries them.

Attributes:

Name Type Description
sleep_stages list[HealthSleepStage] | None

List of sleep stages.

Source code in backend/app/modules/health/health_sleep/schema.py
321
322
323
324
325
326
327
328
class HealthSleepBase(HealthSleepCore):
    """The sleep fields with the sleep stages, the base of every schema that carries them.

    Attributes:
        sleep_stages (list[HealthSleepStage] | None): List of sleep stages.
    """

    sleep_stages: Sequence[HealthSleepStage] | None = Field(default=None, description="List of sleep stages")

HealthSleepCore

Bases: BaseModel

Pydantic model representing the sleep fields every sleep schema shares, without the sleep stages.

This model defines the structure and validation rules for sleep-related health metrics, including sleep duration, quality scores, heart rate variability, oxygen saturation, respiration rates, and sleep stages.

Attributes:

Name Type Description
date date | None

Calendar date of the sleep session.

sleep_start_time_gmt datetime | None

Start time of sleep in GMT.

sleep_end_time_gmt datetime | None

End time of sleep in GMT.

sleep_start_time_local datetime | None

Start time of sleep in local time.

sleep_end_time_local datetime | None

End time of sleep in local time.

total_sleep_seconds StrictInt | None

Total duration of sleep in seconds (>= 0).

nap_time_seconds StrictInt | None

Duration of naps in seconds (>= 0).

unmeasurable_sleep_seconds StrictInt | None

Unmeasurable sleep duration in seconds (>= 0).

deep_sleep_seconds StrictInt | None

Duration of deep sleep in seconds (>= 0).

light_sleep_seconds StrictInt | None

Duration of light sleep in seconds (>= 0).

rem_sleep_seconds StrictInt | None

Duration of REM sleep in seconds (>= 0).

awake_sleep_seconds StrictInt | None

Duration of awake time in seconds (>= 0).

avg_heart_rate StrictInt | None

Average heart rate during sleep (20-220 bpm).

min_heart_rate StrictInt | None

Minimum heart rate during sleep (20-220 bpm).

max_heart_rate StrictInt | None

Maximum heart rate during sleep (20-220 bpm).

avg_spo2_percent StrictInt | None

Average SpO2 oxygen saturation percentage (70-100%).

lowest_spo2_percent StrictInt | None

Lowest SpO2 reading during sleep (70-100%).

highest_spo2_percent StrictInt | None

Highest SpO2 reading during sleep (70-100%).

avg_respiration StrictInt | None

Average respiration rate (>= 0).

lowest_respiration StrictInt | None

Lowest respiration rate (>= 0).

highest_respiration StrictInt | None

Highest respiration rate (>= 0).

avg_stress_level StrictInt | None

Average stress level (0-100).

awake_count StrictInt | None

Number of times awake during sleep (>= 0).

restless_moments_count StrictInt | None

Number of restless moments during sleep (>= 0).

sleep_score_overall StrictInt | None

Overall sleep score (0-100).

sleep_score_duration SleepScore | None

Sleep duration score.

sleep_score_quality SleepScore | None

Sleep quality score.

sleep_stages list[SleepStage] | None

List of sleep stages.

hrv_status HRVStatus | None

Heart rate variability status.

resting_heart_rate StrictInt | None

Resting heart rate (20-220 bpm).

avg_skin_temp_deviation StrictFloat | None

Average skin temperature deviation.

awake_count_score SleepScore | None

Awake count score.

rem_percentage_score SleepScore | None

REM percentage score.

deep_percentage_score SleepScore | None

Deep sleep percentage score.

light_percentage_score SleepScore | None

Light sleep percentage score.

avg_sleep_stress StrictInt | None

Average sleep stress (0-100).

sleep_stress_score SleepScore | None

Sleep stress score.

Model Configuration
  • Allows population from ORM attributes
  • Forbids extra fields
  • Validates on assignment
  • Uses enum values in serialization
Validators

validate_sleep_times: Ensures sleep start time is before sleep end time for both GMT and local time zones.

Source code in backend/app/modules/health/health_sleep/schema.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class HealthSleepCore(BaseModel):
    """Pydantic model representing the sleep fields every sleep schema shares, without the sleep stages.

    This model defines the structure and validation rules for sleep-related health metrics,
    including sleep duration, quality scores, heart rate variability, oxygen saturation,
    respiration rates, and sleep stages.

    Attributes:
        date (datetime_date | None): Calendar date of the sleep session.
        sleep_start_time_gmt (datetime | None): Start time of sleep in GMT.
        sleep_end_time_gmt (datetime | None): End time of sleep in GMT.
        sleep_start_time_local (datetime | None): Start time of sleep in local time.
        sleep_end_time_local (datetime | None): End time of sleep in local time.
        total_sleep_seconds (StrictInt | None): Total duration of sleep in seconds (>= 0).
        nap_time_seconds (StrictInt | None): Duration of naps in seconds (>= 0).
        unmeasurable_sleep_seconds (StrictInt | None): Unmeasurable sleep duration in seconds (>= 0).
        deep_sleep_seconds (StrictInt | None): Duration of deep sleep in seconds (>= 0).
        light_sleep_seconds (StrictInt | None): Duration of light sleep in seconds (>= 0).
        rem_sleep_seconds (StrictInt | None): Duration of REM sleep in seconds (>= 0).
        awake_sleep_seconds (StrictInt | None): Duration of awake time in seconds (>= 0).
        avg_heart_rate (StrictInt | None): Average heart rate during sleep (20-220 bpm).
        min_heart_rate (StrictInt | None): Minimum heart rate during sleep (20-220 bpm).
        max_heart_rate (StrictInt | None): Maximum heart rate during sleep (20-220 bpm).
        avg_spo2_percent (StrictInt | None): Average SpO2 oxygen saturation percentage (70-100%).
        lowest_spo2_percent (StrictInt | None): Lowest SpO2 reading during sleep (70-100%).
        highest_spo2_percent (StrictInt | None): Highest SpO2 reading during sleep (70-100%).
        avg_respiration (StrictInt | None): Average respiration rate (>= 0).
        lowest_respiration (StrictInt | None): Lowest respiration rate (>= 0).
        highest_respiration (StrictInt | None): Highest respiration rate (>= 0).
        avg_stress_level (StrictInt | None): Average stress level (0-100).
        awake_count (StrictInt | None): Number of times awake during sleep (>= 0).
        restless_moments_count (StrictInt | None): Number of restless moments during sleep (>= 0).
        sleep_score_overall (StrictInt | None): Overall sleep score (0-100).
        sleep_score_duration (SleepScore | None): Sleep duration score.
        sleep_score_quality (SleepScore | None): Sleep quality score.
        sleep_stages (list[SleepStage] | None): List of sleep stages.
        hrv_status (HRVStatus | None): Heart rate variability status.
        resting_heart_rate (StrictInt | None): Resting heart rate (20-220 bpm).
        avg_skin_temp_deviation (StrictFloat | None): Average skin temperature deviation.
        awake_count_score (SleepScore | None): Awake count score.
        rem_percentage_score (SleepScore | None): REM percentage score.
        deep_percentage_score (SleepScore | None): Deep sleep percentage score.
        light_percentage_score (SleepScore | None): Light sleep percentage score.
        avg_sleep_stress (StrictInt | None): Average sleep stress (0-100).
        sleep_stress_score (SleepScore | None): Sleep stress score.

    Model Configuration:
        - Allows population from ORM attributes
        - Forbids extra fields
        - Validates on assignment
        - Uses enum values in serialization

    Validators:
        validate_sleep_times: Ensures sleep start time is before sleep end time
                             for both GMT and local time zones.
    """

    date: datetime_date | None = Field(default=None, description="Calendar date of the sleep session")
    sleep_start_time_gmt: datetime | None = Field(default=None, description="Start time of sleep in GMT")
    sleep_end_time_gmt: datetime | None = Field(default=None, description="End time of sleep in GMT")
    sleep_start_time_local: datetime | None = Field(default=None, description=_LOCAL_START_DESCRIPTION)
    sleep_end_time_local: datetime | None = Field(default=None, description=_LOCAL_END_DESCRIPTION)
    total_sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Total duration of sleep in seconds"
    )
    nap_time_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Duration of naps in seconds"
    )
    unmeasurable_sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Unmeasurable sleep duration in seconds"
    )
    deep_sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Duration of deep sleep in seconds"
    )
    light_sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Duration of light sleep in seconds"
    )
    rem_sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Duration of REM sleep in seconds"
    )
    awake_sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Duration of awake time in seconds"
    )
    avg_heart_rate: StrictInt | None = Field(
        default=None, ge=20, le=220, description="Average heart rate during sleep in beats per minute"
    )
    min_heart_rate: StrictInt | None = Field(
        default=None, ge=20, le=220, description="Minimum heart rate during sleep in beats per minute"
    )
    max_heart_rate: StrictInt | None = Field(
        default=None, ge=20, le=220, description="Maximum heart rate during sleep in beats per minute"
    )
    avg_spo2_percent: StrictInt | None = Field(
        default=None,
        ge=70,
        le=100,
        description="Average SpO2 oxygen saturation as a percentage (70-100)",
    )
    lowest_spo2_percent: StrictInt | None = Field(
        default=None, ge=70, le=100, description="Lowest SpO2 reading during sleep as a percentage (70-100)"
    )
    highest_spo2_percent: StrictInt | None = Field(
        default=None, ge=70, le=100, description="Highest SpO2 reading during sleep as a percentage (70-100)"
    )
    avg_respiration: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Average respiration rate in breaths per minute"
    )
    lowest_respiration: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Lowest respiration rate in breaths per minute"
    )
    highest_respiration: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Highest respiration rate in breaths per minute"
    )
    avg_stress_level: StrictInt | None = Field(
        default=None, ge=0, le=100, description="Average stress level, a score from 0 to 100"
    )
    awake_count: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Number of times awake during sleep"
    )
    restless_moments_count: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Number of restless moments during sleep"
    )
    sleep_score_overall: StrictInt | None = Field(default=None, ge=0, le=100, description="Overall sleep score (0-100)")
    sleep_score_duration: SleepScore | None = Field(default=None, description="Sleep duration score")
    sleep_score_quality: SleepScore | None = Field(default=None, description="Sleep quality score")
    hrv_status: HRVStatus | None = Field(default=None, description="Heart rate variability status")
    resting_heart_rate: StrictInt | None = Field(
        default=None, ge=20, le=220, description="Resting heart rate in beats per minute"
    )
    avg_skin_temp_deviation: StrictFloat | None = Field(
        default=None,
        ge=-_NUMERIC_10_2_MAX,
        le=_NUMERIC_10_2_MAX,
        description="Average skin temperature deviation from the baseline in degrees Celsius",
    )
    awake_count_score: SleepScore | None = Field(default=None, description="Awake count score")
    rem_percentage_score: SleepScore | None = Field(default=None, description="REM percentage score")
    deep_percentage_score: SleepScore | None = Field(default=None, description="Deep sleep percentage score")
    light_percentage_score: SleepScore | None = Field(default=None, description="Light sleep percentage score")
    avg_sleep_stress: StrictInt | None = Field(
        default=None, ge=0, le=100, description="Average sleep stress, a score from 0 to 100"
    )
    sleep_stress_score: SleepScore | None = Field(default=None, description="Sleep stress score")

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

    @model_validator(mode="after")
    def validate_sleep_times(self) -> "HealthSleepCore":
        """Validate sleep start < end, reading a time without an offset as UTC."""
        if (
            self.sleep_start_time_gmt is not None
            and self.sleep_end_time_gmt is not None
            and core_timezone.to_utc_aware(self.sleep_start_time_gmt)
            >= core_timezone.to_utc_aware(self.sleep_end_time_gmt)
        ):
            raise ValueError("Sleep start time must be before sleep end time")

        if (
            self.sleep_start_time_local is not None
            and self.sleep_end_time_local is not None
            and core_timezone.to_utc_aware(self.sleep_start_time_local)
            >= core_timezone.to_utc_aware(self.sleep_end_time_local)
        ):
            raise ValueError("Sleep start time (local) must be before sleep end time (local)")

        return self

validate_sleep_times

validate_sleep_times()

Validate sleep start < end, reading a time without an offset as UTC.

Source code in backend/app/modules/health/health_sleep/schema.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
@model_validator(mode="after")
def validate_sleep_times(self) -> "HealthSleepCore":
    """Validate sleep start < end, reading a time without an offset as UTC."""
    if (
        self.sleep_start_time_gmt is not None
        and self.sleep_end_time_gmt is not None
        and core_timezone.to_utc_aware(self.sleep_start_time_gmt)
        >= core_timezone.to_utc_aware(self.sleep_end_time_gmt)
    ):
        raise ValueError("Sleep start time must be before sleep end time")

    if (
        self.sleep_start_time_local is not None
        and self.sleep_end_time_local is not None
        and core_timezone.to_utc_aware(self.sleep_start_time_local)
        >= core_timezone.to_utc_aware(self.sleep_end_time_local)
    ):
        raise ValueError("Sleep start time (local) must be before sleep end time (local)")

    return self

HealthSleepCreate

Bases: HealthSleepWrite

Schema for creating a health sleep record.

The date is optional; service fills it in when the client sends none.

Source code in backend/app/modules/health/health_sleep/schema.py
372
373
374
375
376
377
378
class HealthSleepCreate(HealthSleepWrite):
    """Schema for creating a health sleep record.

    The date is optional; ``service`` fills it in when the client sends none.
    """

    sleep_stages: Sequence[HealthSleepStageWrite] | None = Field(default=None, description="List of sleep stages")

HealthSleepIdentity

Bases: HealthSleepCore

The stored identity and provenance every sleep read carries, with the sleep fields but not the stages.

Attributes:

Name Type Description
garminconnect_sleep_id StrictStr | None

Garmin Connect sleep record ID.

source Source | None

Source of the sleep data.

user_id UUID

Foreign key reference to the user.

id UUID

Unique identifier for the sleep record to update or retrieve.

version StrictInt

Optimistic-concurrency counter, also sent as the ETag.

Source code in backend/app/modules/health/health_sleep/schema.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
class HealthSleepIdentity(HealthSleepCore):
    """The stored identity and provenance every sleep read carries, with the sleep fields but not the stages.

    Attributes:
        garminconnect_sleep_id (StrictStr | None): Garmin Connect sleep record ID.
        source (Source | None): Source of the sleep data.
        user_id (uuid.UUID): Foreign key reference to the user.
        id (uuid.UUID): Unique identifier for the sleep record to update or retrieve.
        version (StrictInt): Optimistic-concurrency counter, also sent as the ETag.
    """

    garminconnect_sleep_id: StrictStr | None = Field(
        default=None, min_length=1, description="Garmin Connect sleep record ID"
    )
    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the sleep data")
    id: uuid.UUID = Field(..., description="Unique identifier for the sleep record to update")
    user_id: uuid.UUID = Field(..., description="Foreign key reference to the user")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    updated_at: datetime = Field(..., description="When the record last changed, set by the server")

HealthSleepImport

Bases: HealthSleepWrite

Sleep record written by the server itself: a provider sync or a profile import.

Unlike :class:HealthSleepCreate it carries the provenance, which a client never sets. Every server-side writer of source takes Health<Kind>Import (create) or Health<Kind>ImportUpdate.

Attributes:

Name Type Description
garminconnect_sleep_id StrictStr | None

Garmin Connect sleep record ID.

source Source

The source the record came from; manual when none is given.

Source code in backend/app/modules/health/health_sleep/schema.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
class HealthSleepImport(HealthSleepWrite):
    """Sleep record written by the server itself: a provider sync or a profile import.

    Unlike :class:`HealthSleepCreate` it carries the provenance, which a client never sets. Every
    server-side writer of ``source`` takes ``Health<Kind>Import`` (create) or ``Health<Kind>ImportUpdate``.

    Attributes:
        garminconnect_sleep_id (StrictStr | None): Garmin Connect sleep record ID.
        source (Source): The source the record came from; ``manual`` when none is given.
    """

    garminconnect_sleep_id: StrictStr | None = Field(
        default=None, min_length=1, description="Garmin Connect sleep record ID"
    )
    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the sleep data")
    sleep_start_time_gmt: core_types.ImportedInstant | None = Field(default=None, description="Start time of sleep")
    sleep_end_time_gmt: core_types.ImportedInstant | None = Field(default=None, description="End time of sleep")
    sleep_stages: Sequence[HealthSleepStageImport] | None = Field(default=None, description="List of sleep stages")

HealthSleepImportUpdate

Bases: NotClearable, HealthSleepWrite

Fields a provider sync or a profile import changes on a sleep record, provenance included.

Attributes:

Name Type Description
garminconnect_sleep_id StrictStr | None

Garmin Connect sleep record ID.

source Source | None

The source the record came from.

Source code in backend/app/modules/health/health_sleep/schema.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
class HealthSleepImportUpdate(core_partial_update.NotClearable, HealthSleepWrite):
    """Fields a provider sync or a profile import changes on a sleep record, provenance included.

    Attributes:
        garminconnect_sleep_id (StrictStr | None): Garmin Connect sleep record ID.
        source (Source | None): The source the record came from.
    """

    not_clearable: ClassVar[tuple[str, ...]] = (*HealthSleepUpdate.not_clearable, "source")

    garminconnect_sleep_id: StrictStr | None = Field(
        default=None, min_length=1, description="Garmin Connect sleep record ID"
    )
    source: Source | None = Field(default=None, description="Source of the sleep data")
    sleep_start_time_gmt: core_types.ImportedInstant | None = Field(default=None, description="Start time of sleep")
    sleep_end_time_gmt: core_types.ImportedInstant | None = Field(default=None, description="End time of sleep")
    sleep_stages: Sequence[HealthSleepStageImport] | None = Field(default=None, description="List of sleep stages")

HealthSleepListItem

Bases: HealthSleepIdentity

A sleep record as the list returns it: no stages, only whether the record has any.

The stages are on GET /health/sleep/{health_sleep_id}.

Attributes:

Name Type Description
has_sleep_stages bool

Whether the record has at least one sleep stage. Read from a stored row's sleep_stages.

Source code in backend/app/modules/health/health_sleep/schema.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
class HealthSleepListItem(HealthSleepIdentity):
    """A sleep record as the list returns it: no stages, only whether the record has any.

    The stages are on ``GET /health/sleep/{health_sleep_id}``.

    Attributes:
        has_sleep_stages (bool): Whether the record has at least one sleep stage. Read from a stored row's
            ``sleep_stages``.
    """

    has_sleep_stages: Annotated[bool, BeforeValidator(_has_stages)] = Field(
        validation_alias=AliasChoices("has_sleep_stages", "sleep_stages"),
        description="Whether the record has at least one sleep stage; the stages are on the record itself",
    )

HealthSleepRead

Bases: HealthSleepIdentity, HealthSleepBase

Read schema for a health sleep record, with its sleep stages.

Source code in backend/app/modules/health/health_sleep/schema.py
402
403
class HealthSleepRead(HealthSleepIdentity, HealthSleepBase):
    """Read schema for a health sleep record, with its sleep stages."""

HealthSleepStage

Bases: BaseModel

Represents a sleep stage with timing and duration information.

This model captures details about individual sleep stages within a sleep session, including the type of stage, when it occurred, and how long it lasted.

Attributes:

Name Type Description
stage_type StoredSleepStageType | None

The classification of the sleep stage (e.g., light, deep, REM).

start_time_gmt datetime | None

The beginning timestamp of the sleep stage in GMT timezone.

end_time_gmt datetime | None

The ending timestamp of the sleep stage in GMT timezone.

duration_seconds StrictInt | None

The length of the sleep stage in seconds. Must be non-negative.

Source code in backend/app/modules/health/health_sleep/schema.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class HealthSleepStage(BaseModel):
    """Represents a sleep stage with timing and duration information.

    This model captures details about individual sleep stages within a sleep session,
    including the type of stage, when it occurred, and how long it lasted.

    Attributes:
        stage_type: The classification of the sleep stage (e.g., light, deep, REM).
        start_time_gmt: The beginning timestamp of the sleep stage in GMT timezone.
        end_time_gmt: The ending timestamp of the sleep stage in GMT timezone.
        duration_seconds: The length of the sleep stage in seconds. Must be non-negative.
    """

    stage_type: StoredSleepStageType | None = Field(default=None, description="Type of sleep stage")
    start_time_gmt: datetime | None = Field(default=None, description="Start time of the stage in GMT")
    end_time_gmt: datetime | None = Field(default=None, description="End time of the stage in GMT")
    duration_seconds: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Duration of the stage in seconds"
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
    )

    @field_serializer("start_time_gmt", "end_time_gmt")
    def serialize_time(self, value: datetime | None) -> str | None:
        """Dump a stage time as ISO 8601 text in every mode, as the JSON column that stores the stages requires.

        Args:
            value: The time, or ``None``.

        Returns:
            The time as the API writes it in JSON, or ``None``.
        """
        return None if value is None else _DATETIME.dump_python(value, mode="json")

serialize_time

serialize_time(value)

Dump a stage time as ISO 8601 text in every mode, as the JSON column that stores the stages requires.

Parameters:

Name Type Description Default
value datetime | None

The time, or None.

required

Returns:

Type Description
str | None

The time as the API writes it in JSON, or None.

Source code in backend/app/modules/health/health_sleep/schema.py
135
136
137
138
139
140
141
142
143
144
145
@field_serializer("start_time_gmt", "end_time_gmt")
def serialize_time(self, value: datetime | None) -> str | None:
    """Dump a stage time as ISO 8601 text in every mode, as the JSON column that stores the stages requires.

    Args:
        value: The time, or ``None``.

    Returns:
        The time as the API writes it in JSON, or ``None``.
    """
    return None if value is None else _DATETIME.dump_python(value, mode="json")

HealthSleepStageImport

Bases: HealthSleepStageWrite

A sleep stage the server writes: a provider sync or a profile import, which may hand over the stored number.

Source code in backend/app/modules/health/health_sleep/schema.py
346
347
348
349
350
351
class HealthSleepStageImport(HealthSleepStageWrite):
    """A sleep stage the server writes: a provider sync or a profile import, which may hand over the stored number."""

    stage_type: StoredSleepStageType | None = Field(default=None, description="Type of sleep stage")
    start_time_gmt: core_types.ImportedInstant | None = Field(default=None, description="Start time of the stage")
    end_time_gmt: core_types.ImportedInstant | None = Field(default=None, description="End time of the stage")

HealthSleepStageWrite

Bases: HealthSleepStage

A sleep stage a client writes.

Its times carry a UTC offset and are bounded, which a stored stage read back need not be.

Source code in backend/app/modules/health/health_sleep/schema.py
331
332
333
334
335
336
337
338
339
340
341
342
343
class HealthSleepStageWrite(HealthSleepStage):
    """A sleep stage a client writes.

    Its times carry a UTC offset and are bounded, which a stored stage read back need not be.
    """

    stage_type: SleepStageType | None = Field(default=None, description="Type of sleep stage")
    start_time_gmt: core_types.RecordInstant | None = Field(
        default=None, description="Start time of the stage, with a UTC offset"
    )
    end_time_gmt: core_types.RecordInstant | None = Field(
        default=None, description="End time of the stage, with a UTC offset"
    )

HealthSleepUpdate

Bases: NotClearable, HealthSleepWrite

Schema for the fields a PATCH changes on a sleep record.

The record is named by the path, so the body carries neither an id nor an owner; only the fields present are changed.

Source code in backend/app/modules/health/health_sleep/schema.py
434
435
436
437
438
439
440
441
442
443
class HealthSleepUpdate(core_partial_update.NotClearable, HealthSleepWrite):
    """Schema for the fields a PATCH changes on a sleep record.

    The record is named by the path, so the body carries neither an id nor an owner; only the
    fields present are changed.
    """

    not_clearable: ClassVar[tuple[str, ...]] = ("date",)

    sleep_stages: Sequence[HealthSleepStageWrite] | None = Field(default=None, description="List of sleep stages")

HealthSleepWrite

Bases: HealthSleepCore

Sleep fields a client writes: the date and times are bounded, which a stored row read back need not be.

Source code in backend/app/modules/health/health_sleep/schema.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class HealthSleepWrite(HealthSleepCore):
    """Sleep fields a client writes: the date and times are bounded, which a stored row read back need not be."""

    date: core_types.RecordDate | None = Field(default=None, description="Calendar date of the sleep session")
    sleep_start_time_gmt: core_types.RecordInstant | None = Field(
        default=None, description="Start time of sleep as an instant, with a UTC offset"
    )
    sleep_end_time_gmt: core_types.RecordInstant | None = Field(
        default=None, description="End time of sleep as an instant, with a UTC offset"
    )
    sleep_start_time_local: core_types.RecordLocalDateTime | None = Field(
        default=None, description=_LOCAL_START_DESCRIPTION
    )
    sleep_end_time_local: core_types.RecordLocalDateTime | None = Field(
        default=None, description=_LOCAL_END_DESCRIPTION
    )

SleepScore

Bases: Enum

Enumeration of sleep quality score levels.

Attributes:

Name Type Description
EXCELLENT str

Represents excellent sleep quality.

GOOD str

Represents good sleep quality.

FAIR str

Represents fair sleep quality.

POOR str

Represents poor sleep quality.

Source code in backend/app/modules/health/health_sleep/schema.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class SleepScore(Enum):
    """Enumeration of sleep quality score levels.

    Attributes:
        EXCELLENT (str): Represents excellent sleep quality.
        GOOD (str): Represents good sleep quality.
        FAIR (str): Represents fair sleep quality.
        POOR (str): Represents poor sleep quality.
    """

    EXCELLENT = "EXCELLENT"
    GOOD = "GOOD"
    FAIR = "FAIR"
    POOR = "POOR"

SleepStageType

Bases: StoredStrEnum

The stages of a sleep session; stored is the Garmin activity level kept in the sleep stages.

Attributes:

Name Type Description
DEEP

Deep sleep, characterized by slow brain waves and muscle relaxation.

LIGHT

Light sleep, the transition between wakefulness and deep sleep.

REM

Rapid Eye Movement sleep, associated with vivid dreams and mental activity.

AWAKE

Awake, the stage when the person is conscious and not sleeping.

Source code in backend/app/modules/health/health_sleep/schema.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class SleepStageType(StoredStrEnum):
    """The stages of a sleep session; ``stored`` is the Garmin activity level kept in the sleep stages.

    Attributes:
        DEEP: Deep sleep, characterized by slow brain waves and muscle relaxation.
        LIGHT: Light sleep, the transition between wakefulness and deep sleep.
        REM: Rapid Eye Movement sleep, associated with vivid dreams and mental activity.
        AWAKE: Awake, the stage when the person is conscious and not sleeping.
    """

    DEEP = ("deep", 0)
    LIGHT = ("light", 1)
    REM = ("rem", 2)
    AWAKE = ("awake", 3)

Source

Bases: Enum

Enum representing the source of sleep health data.

Attributes:

Name Type Description
MANUAL

Sleep data entered manually.

GARMIN

Sleep data sourced from Garmin devices or services.

Source code in backend/app/modules/health/health_sleep/schema.py
44
45
46
47
48
49
50
51
52
53
class Source(Enum):
    """Enum representing the source of sleep health data.

    Attributes:
        MANUAL: Sleep data entered manually.
        GARMIN: Sleep data sourced from Garmin devices or services.
    """

    MANUAL = "manual"
    GARMIN = "garmin"

Health steps

FastAPI router for health steps endpoints.

create_health_steps

create_health_steps(request, health_steps, token_user_id, db, response)

Create health steps data for a user.

A date that already has a record is answered with a 409; change it with PATCH /{id}.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_steps HealthSteps

The health steps data to create, including the date and step count.

required
token_user_id UUID

The ID of the authenticated user extracted from the access token.

required
db Session

Database session dependency for database operations.

required
response Response

The response, whose Location names where the record is read.

required

Returns:

Type Description
HealthStepsRead

health_steps_schema.HealthSteps: The created health steps data.

Source code in backend/app/modules/health/health_steps/router.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
@router.post(
    "",
    response_model=health_steps_schema.HealthStepsRead,
    status_code=status.HTTP_201_CREATED,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def create_health_steps(
    request: Request,
    health_steps: health_steps_schema.HealthStepsCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_steps_schema.HealthStepsRead:
    """Create health steps data for a user.

    A date that already has a record is answered with a 409; change it with ``PATCH /{id}``.

    Args:
        request: The incoming request, read by the rate limiter.
        health_steps (health_steps_schema.HealthSteps): The health steps data to create,
            including the date and step count.
        token_user_id (uuid.UUID): The ID of the authenticated user extracted from the
            access token.
        db (Session): Database session dependency for database operations.
        response: The response, whose ``Location`` names where the record is read.

    Returns:
        health_steps_schema.HealthSteps: The created health steps data.

    """
    created = health_steps_service.create_health_steps(token_user_id, health_steps, db)
    core_location.set_location(response, request, "read_health_steps_by_id", health_steps_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_health_steps

delete_health_steps(request, health_steps_id, token_user_id, if_match, db)

Delete a health steps record for the authenticated user.

This endpoint removes a specific health steps entry from the database for the user identified by the access token. The user must have 'health:write' scope permission.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_steps_id UUID

The unique identifier of the health steps record to delete.

required
token_user_id UUID

The user ID extracted from the access token.

required
if_match IfMatch

The If-Match precondition.

required
db Session

Database session dependency for executing the delete operation.

required

Returns:

Name Type Description
None None

This function does not return a value.

Raises:

Type Description
PreconditionFailedError

If the record changed since the client read it.

NotFoundError

If the user has no such record.

Source code in backend/app/modules/health/health_steps/router.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
@router.delete(
    "/{health_steps_id}",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_health_steps(
    request: Request,
    health_steps_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> None:
    """Delete a health steps record for the authenticated user.

    This endpoint removes a specific health steps entry from the database for the user
    identified by the access token. The user must have 'health:write' scope permission.

    Args:
        request: The incoming request, read by the rate limiter.
        health_steps_id (uuid.UUID): The unique identifier of the health steps record to delete.
        token_user_id (uuid.UUID): The user ID extracted from the access token.
        if_match: The ``If-Match`` precondition.
        db (Session): Database session dependency for executing the delete operation.

    Returns:
        None: This function does not return a value.

    Raises:
        PreconditionFailedError: If the record changed since the client read it.
        NotFoundError: If the user has no such record.
    """
    # Deletes entry from database
    health_steps_service.delete_health_steps(token_user_id, health_steps_id, db, if_match=if_match)

edit_health_steps

edit_health_steps(request, health_steps_id, health_steps, token_user_id, db, response, if_match)

Edit health steps data for a user.

This endpoint updates existing health steps records in the database for the authenticated user. Requires 'health:write' scope for authorization.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_steps_id UuidId

ID of the record to change.

required
health_steps HealthSteps

The health steps data to be updated, containing the new values for the health steps record.

required
token_user_id UUID

The user ID extracted from the JWT access token, used to identify the user making the request.

required
db Session

Database session dependency for performing database operations.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
HealthStepsRead

health_steps_schema.HealthSteps: The updated health steps record with the new values as stored in the database.

Raises:

Type Description
NotFoundError

If the user has no such record.

PreconditionFailedError

If the record changed since the client read it.

Source code in backend/app/modules/health/health_steps/router.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@router.patch(
    "/{health_steps_id}",
    response_model=health_steps_schema.HealthStepsRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_health_steps(
    request: Request,
    health_steps_id: core_dependencies.UuidId,
    health_steps: health_steps_schema.HealthStepsUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> health_steps_schema.HealthStepsRead:
    """Edit health steps data for a user.

    This endpoint updates existing health steps records in the database for the authenticated user.
    Requires 'health:write' scope for authorization.

    Args:
        request: The incoming request, read by the rate limiter.
        health_steps_id: ID of the record to change.
        health_steps (health_steps_schema.HealthSteps): The health steps data to be updated,
            containing the new values for the health steps record.
        token_user_id (uuid.UUID): The user ID extracted from the JWT access token, used to identify
            the user making the request.
        db (Session): Database session dependency for performing database operations.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        health_steps_schema.HealthSteps: The updated health steps record with the new values
            as stored in the database.

    Raises:
        NotFoundError: If the user has no such record.
        PreconditionFailedError: If the record changed since the client read it.
    """
    # Updates the health_steps in the database and returns it
    updated = health_steps_service.edit_health_steps(
        token_user_id, health_steps_id, health_steps, db, if_match=if_match
    )
    core_etag.set_etag(response, updated.version)
    return updated

read_health_steps_all_pagination

read_health_steps_all_pagination(token_user_id, db, page, date_range, interval=None)

Retrieve paginated health steps records for the authenticated user.

One page of records, newest first, optionally limited to an interval. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
page ListPage

The requested page and page size.

required
interval Annotated[Interval | None, Query(description='Look back from today over this interval; ignored when `start_date` or `end_date` is given')]

Optional interval looking back from today; ignored when a date range is given.

None
date_range DateRangeQuery

Optional inclusive start and end dates, which replace the interval.

required

Returns:

Type Description
Page[HealthStepsRead]

The page of records with the total matching the interval.

Source code in backend/app/modules/health/health_steps/router.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@router.get(
    "",
    response_model=core_pagination.Page[health_steps_schema.HealthStepsRead],
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_steps_all_pagination(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    page: core_pagination.ListPage,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval | None,
        Query(description="Look back from today over this interval; ignored when `start_date` or `end_date` is given"),
    ] = None,
) -> core_pagination.Page[health_steps_schema.HealthStepsRead]:
    """Retrieve paginated health steps records for the authenticated user.

    One page of records, newest first, optionally limited to an interval. Access is
    restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        page: The requested page and page size.
        interval: Optional interval looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates, which replace the interval.

    Returns:
        The page of records with the total matching the interval.
    """
    return health_steps_service.list_health_steps(
        token_user_id,
        db,
        page_number=page.page_number,
        num_records=page.num_records,
        interval=interval,
        date_range=date_range,
    )

read_health_steps_by_id

read_health_steps_by_id(health_steps_id, token_user_id, db, response)

Retrieve one of the authenticated user's steps records; its ETag is the version for If-Match.

Source code in backend/app/modules/health/health_steps/router.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@router.get(
    "/{health_steps_id}",
    response_model=health_steps_schema.HealthStepsRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_steps_by_id(
    health_steps_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_steps_schema.HealthStepsRead:
    """Retrieve one of the authenticated user's steps records; its ``ETag`` is the version for ``If-Match``."""
    record = health_steps_service.get_health_steps(token_user_id, health_steps_id, db)
    core_etag.set_etag(response, record.version)
    return record

read_health_steps_chart

read_health_steps_chart(token_user_id, db, date_range, interval=health_constants.Interval.LAST_7_DAYS)

Chart the authenticated user's steps over an interval.

One aggregated point per day, week or month depending on the interval, so the response stays small however long the history. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
interval Annotated[Interval, Query(description='Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given')]

The window to chart, looking back from today; ignored when a date range is given.

LAST_7_DAYS
date_range DateRangeQuery

Optional inclusive start and end dates to chart instead of the interval.

required

Returns:

Type Description
HealthChartSeries

The interval's bucket size and its points, oldest first.

Source code in backend/app/modules/health/health_steps/router.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
@router.get(
    "/chart",
    response_model=health_schema.HealthChartSeries,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_steps_chart(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval,
        Query(
            description="Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given"
        ),
    ] = health_constants.Interval.LAST_7_DAYS,
) -> health_schema.HealthChartSeries:
    """Chart the authenticated user's steps over an interval.

    One aggregated point per day, week or month depending on the interval, so the response stays small
    however long the history. Access is restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        interval: The window to chart, looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates to chart instead of the interval.

    Returns:
        The interval's bucket size and its points, oldest first.
    """
    return health_steps_service.get_health_steps_chart(token_user_id, interval, db, date_range=date_range)

Pydantic request and response shapes for health steps records.

HealthStepsBase

Bases: BaseModel

Base model for health steps data.

Represents the core attributes of a user's step count record, including the user reference, date of the record and number of steps taken.

Attributes:

Name Type Description
date date | None

Calendar date of the steps record. Optional field.

steps StrictInt | None

Number of steps taken. Must be a non-negative integer. Optional field.

Configuration
  • from_attributes: Allows model to be populated from ORM objects.
  • extra: Forbids any extra fields not defined in the model.
  • validate_assignment: Validates field values when assigned after model creation.
  • use_enum_values: Uses enum values instead of enum objects in serialization.
Source code in backend/app/modules/health/health_steps/schema.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class HealthStepsBase(BaseModel):
    """Base model for health steps data.

    Represents the core attributes of a user's step count record, including the user reference,
    date of the record and number of steps taken.

    Attributes:
        date (datetime_date | None): Calendar date of the steps record. Optional field.
        steps (StrictInt | None): Number of steps taken. Must be a non-negative integer. Optional field.

    Configuration:
        - from_attributes: Allows model to be populated from ORM objects.
        - extra: Forbids any extra fields not defined in the model.
        - validate_assignment: Validates field values when assigned after model creation.
        - use_enum_values: Uses enum values instead of enum objects in serialization.
    """

    date: datetime_date | None = Field(default=None, description="Calendar date of the steps")

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

HealthStepsCreate

Bases: HealthStepsWrite

Schema for creating a health steps record.

The date is optional; service fills it in when the client sends none.

Source code in backend/app/modules/health/health_steps/schema.py
63
64
65
66
67
68
69
class HealthStepsCreate(HealthStepsWrite):
    """Schema for creating a health steps record.

    The date is optional; ``service`` fills it in when the client sends none.
    """

    steps: StepsCount = Field(..., description="Number of steps taken")

HealthStepsImport

Bases: HealthStepsCreate

Steps record written by the server itself: a provider sync or a profile import.

Unlike :class:HealthStepsCreate it carries the provenance, which a client never sets. Every server-side writer of source takes Health<Kind>Import (create) or Health<Kind>ImportUpdate.

Attributes:

Name Type Description
source Source

The source the record came from; manual when none is given.

Source code in backend/app/modules/health/health_steps/schema.py
104
105
106
107
108
109
110
111
112
113
114
class HealthStepsImport(HealthStepsCreate):
    """Steps record written by the server itself: a provider sync or a profile import.

    Unlike :class:`HealthStepsCreate` it carries the provenance, which a client never sets. Every
    server-side writer of ``source`` takes ``Health<Kind>Import`` (create) or ``Health<Kind>ImportUpdate``.

    Attributes:
        source (Source): The source the record came from; ``manual`` when none is given.
    """

    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the steps data")

HealthStepsImportUpdate

Bases: HealthStepsUpdate

Fields a provider sync or a profile import changes on a steps record, provenance included.

Attributes:

Name Type Description
source Source | None

The source the record came from.

Source code in backend/app/modules/health/health_steps/schema.py
117
118
119
120
121
122
123
124
125
126
class HealthStepsImportUpdate(HealthStepsUpdate):
    """Fields a provider sync or a profile import changes on a steps record, provenance included.

    Attributes:
        source (Source | None): The source the record came from.
    """

    not_clearable: ClassVar[tuple[str, ...]] = (*HealthStepsUpdate.not_clearable, "source")

    source: Source | None = Field(default=None, description="Source of the steps data")

HealthStepsRead

Bases: HealthStepsBase

Schema for reading health steps records.

Extends the base health steps schema with an identifier field for retrieving or referencing existing steps records in the database.

Attributes:

Name Type Description
source Source | None

Source of the steps data (e.g., device, API, manual entry). Optional field.

id UUID

Unique identifier for the steps record to update. Required field.

user_id UUID

Foreign key reference to the user. Required field.

Source code in backend/app/modules/health/health_steps/schema.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class HealthStepsRead(HealthStepsBase):
    """Schema for reading health steps records.

    Extends the base health steps schema with an identifier field for retrieving
    or referencing existing steps records in the database.

    Attributes:
        source (Source | None): Source of the steps data (e.g., device, API, manual entry). Optional field.
        id (uuid.UUID): Unique identifier for the steps record to update. Required field.
        user_id (uuid.UUID): Foreign key reference to the user. Required field.
    """

    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the steps data")
    id: uuid.UUID = Field(..., description="Unique identifier for the steps record to update")
    steps: StepsCount | None = Field(default=None, description="Number of steps taken")
    user_id: uuid.UUID = Field(..., description="Foreign key reference to the user")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    updated_at: datetime = Field(..., description="When the record last changed, set by the server")

HealthStepsUpdate

Bases: NotClearable, HealthStepsWrite

Schema for the fields a PATCH changes on a steps record.

The record is named by the path, so the body carries neither an id nor an owner; only the fields present are changed.

Source code in backend/app/modules/health/health_steps/schema.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class HealthStepsUpdate(core_partial_update.NotClearable, HealthStepsWrite):
    """Schema for the fields a PATCH changes on a steps record.

    The record is named by the path, so the body carries neither an id nor an owner; only the
    fields present are changed.
    """

    not_clearable: ClassVar[tuple[str, ...]] = ("date", "steps")

    steps: StepsCount | None = Field(default=None, description="Number of steps taken")

HealthStepsWrite

Bases: HealthStepsBase

Steps fields a client writes: the date is bounded, which a stored row read back need not be.

Source code in backend/app/modules/health/health_steps/schema.py
57
58
59
60
class HealthStepsWrite(HealthStepsBase):
    """Steps fields a client writes: the date is bounded, which a stored row read back need not be."""

    date: core_types.RecordDate | None = Field(default=None, description="Calendar date of the steps")

Source

Bases: Enum

An enumeration representing supported sources for the application.

Members

MANUAL: Manually entered data GARMIN: Garmin health data source

Source code in backend/app/modules/health/health_steps/schema.py
18
19
20
21
22
23
24
25
26
27
class Source(Enum):
    """An enumeration representing supported sources for the application.

    Members:
        MANUAL: Manually entered data
        GARMIN: Garmin health data source
    """

    MANUAL = "manual"
    GARMIN = "garmin"

Health targets

FastAPI router for health targets endpoints.

read_health_targets_all

read_health_targets_all(token_user_id, db, response)

Retrieve all health targets for the authenticated user.

This endpoint fetches all health targets associated with the user identified by the access token. It requires the 'health-targets:read' scope for authorization.

Parameters:

Name Type Description Default
token_user_id UUID

The user ID extracted from the JWT access token, automatically injected by the authentication dependency.

required
db Session

SQLAlchemy database session dependency for executing database queries.

required
response Response

The response, which carries the targets' ETag.

required

Returns:

Type Description
HealthTargetsRead | None

health_targets_schema.HealthTargetsRead | None: The health targets object containing all targets for the user, or None if no targets are found.

Source code in backend/app/modules/health/health_targets/router.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@router.get(
    "",
    response_model=health_targets_schema.HealthTargetsRead | None,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health-targets:read"])],
)
def read_health_targets_all(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_targets_schema.HealthTargetsRead | None:
    """Retrieve all health targets for the authenticated user.

    This endpoint fetches all health targets associated with the user identified by the
    access token. It requires the 'health-targets:read' scope for authorization.

    Args:
        token_user_id (uuid.UUID): The user ID extracted from the JWT access token, automatically
            injected by the authentication dependency.
        db (Session): SQLAlchemy database session dependency for executing database queries.
        response: The response, which carries the targets' ETag.

    Returns:
        health_targets_schema.HealthTargetsRead | None: The
            health targets object containing all targets for
            the user, or None if no targets are found.
    """
    targets = health_targets_service.get_health_targets(token_user_id, db)
    if targets is not None:
        core_etag.set_etag(response, targets.version)
    return targets

update_health_targets

update_health_targets(request, health_targets, token_user_id, db, response, if_match)

Update health targets for the authenticated user.

This endpoint allows users to modify their health-related targets such as weight goals, activity targets, or other health metrics.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_targets HealthTargetsUpdate

The health targets to update, containing the new values for the health metrics.

required
token_user_id UUID

The authenticated user's ID extracted from the access token.

required
db Session

Database session dependency for database operations.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
HealthTargetsRead

health_targets_schema.HealthTargetsRead: The updated health targets object reflecting the changes made in the database.

Raises:

Type Description
NotFoundError

If the user has no targets.

PreconditionFailedError

If the targets changed since the client read them.

Source code in backend/app/modules/health/health_targets/router.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@router.patch(
    "",
    response_model=health_targets_schema.HealthTargetsRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health-targets:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def update_health_targets(
    request: Request,
    health_targets: health_targets_schema.HealthTargetsUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> health_targets_schema.HealthTargetsRead:
    """Update health targets for the authenticated user.

    This endpoint allows users to modify their health-related targets such as
    weight goals, activity targets, or other health metrics.

    Args:
        request: The incoming request, read by the rate limiter.
        health_targets: The health targets to update, containing the new values for
            the health metrics.
        token_user_id (uuid.UUID): The authenticated user's ID
            extracted from the access token.
        db (Session): Database session dependency for database
            operations.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        health_targets_schema.HealthTargetsRead: The updated
            health targets object reflecting the changes made
            in the database.

    Raises:
        NotFoundError: If the user has no targets.
        PreconditionFailedError: If the targets changed since the client read them.
    """
    updated = health_targets_service.update_health_targets(health_targets, token_user_id, db, if_match=if_match)
    core_etag.set_etag(response, updated.version)
    return updated

Pydantic request and response shapes for health targets.

HealthTargetsBase

Bases: BaseModel

Base schema for health targets with shared fields.

Attributes:

Name Type Description
weight_kg StrictFloat | None

Target weight in kg.

steps StrictInt | None

Target daily steps count.

sleep_seconds StrictInt | None

Target sleep duration in seconds.

fasting_seconds StrictInt | None

Target fasting duration in seconds.

water_ml StrictFloat | None

Target daily water intake in milliliters.

poop_count StrictInt | None

Target daily bowel movement count.

Source code in backend/app/modules/health/health_targets/schema.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class HealthTargetsBase(BaseModel):
    """Base schema for health targets with shared fields.

    Attributes:
        weight_kg: Target weight in kg.
        steps: Target daily steps count.
        sleep_seconds: Target sleep duration in seconds.
        fasting_seconds: Target fasting duration in seconds.
        water_ml: Target daily water intake in milliliters.
        poop_count: Target daily bowel movement count.
    """

    weight_kg: StrictFloat | None = Field(default=None, gt=0, le=500, description="Target weight in kg")
    steps: StrictInt | None = Field(default=None, ge=0, le=core_types.INT32_MAX, description="Target daily steps count")
    sleep_seconds: StrictInt | None = Field(
        default=None, ge=0, le=86400, description="Target sleep duration in seconds"
    )
    fasting_seconds: StrictInt | None = Field(
        default=None,
        ge=0,
        le=259200,
        description="Target fasting duration in seconds (max 72h)",
    )
    water_ml: StrictFloat | None = Field(
        default=None,
        ge=0,
        le=20000,
        description=("Target daily water intake in milliliters"),
    )
    poop_count: StrictInt | None = Field(
        default=None,
        ge=0,
        le=20,
        description="Target daily bowel movement count",
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
    )

HealthTargetsRead

Bases: HealthTargetsBase

Schema for reading health targets.

Attributes:

Name Type Description
id UUID

Unique identifier for the health target record.

user_id UUID

Foreign key reference to the user.

version StrictInt

Optimistic-concurrency counter, also sent as the ETag.

Source code in backend/app/modules/health/health_targets/schema.py
54
55
56
57
58
59
60
61
62
63
64
65
66
class HealthTargetsRead(HealthTargetsBase):
    """Schema for reading health targets.

    Attributes:
        id: Unique identifier for the health target record.
        user_id: Foreign key reference to the user.
        version: Optimistic-concurrency counter, also sent as the ETag.
    """

    id: uuid.UUID = Field(..., description="Unique identifier for the health target")
    user_id: uuid.UUID = Field(..., description="Foreign key reference to the user")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    updated_at: datetime = Field(..., description="When the record last changed, set by the server")

HealthTargetsUpdate

Bases: HealthTargetsBase

Schema for the fields a PATCH changes on a user's health targets.

The targets belong to the caller, so the body carries neither an id nor an owner; only the fields present are changed.

Source code in backend/app/modules/health/health_targets/schema.py
69
70
71
72
73
74
class HealthTargetsUpdate(HealthTargetsBase):
    """Schema for the fields a PATCH changes on a user's health targets.

    The targets belong to the caller, so the body carries neither an id nor an owner; only the
    fields present are changed.
    """

Health water

FastAPI router for health water intake endpoints.

This module defines the API endpoints for managing water intake records, including CRUD operations with pagination and filtering.

create_health_water

create_health_water(request, health_water, token_user_id, db, response)

Record a water intake for the user's day.

The intake is added to the day's total, so several intakes in one day are all counted.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_water HealthWaterCreate

Water intake data to create.

required
token_user_id CurrentUserId

User ID from the access token.

required
db DbSession

Database session dependency.

required
response Response

The response, whose Location names where the record is read.

required

Returns:

Type Description
HealthWaterRead

The day's HealthWaterRead record, with the intake added.

Source code in backend/app/modules/health/health_water/router.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@router.post(
    "",
    response_model=health_water_schema.HealthWaterRead,
    status_code=status.HTTP_201_CREATED,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:write"],
        )
    ],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def create_health_water(
    request: Request,
    health_water: health_water_schema.HealthWaterCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_water_schema.HealthWaterRead:
    """Record a water intake for the user's day.

    The intake is added to the day's total, so several intakes in one day are all counted.

    Args:
        request: The incoming request, read by the rate limiter.
        health_water: Water intake data to create.
        token_user_id: User ID from the access token.
        db: Database session dependency.
        response: The response, whose ``Location`` names where the record is read.

    Returns:
        The day's HealthWaterRead record, with the intake added.

    """
    created = health_water_service.create_health_water(token_user_id, health_water, db)
    core_location.set_location(response, request, "read_health_water_by_id", health_water_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_health_water

delete_health_water(request, health_water_id, token_user_id, if_match, db)

Delete a water intake record for the authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_water_id UuidId

ID of the water intake record.

required
token_user_id CurrentUserId

User ID from the access token.

required
if_match IfMatch

The If-Match precondition.

required
db DbSession

Database session dependency.

required

Raises:

Type Description
PreconditionFailedError

If the record changed since the client read it.

NotFoundError

If the user has no such record.

Source code in backend/app/modules/health/health_water/router.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
@router.delete(
    "/{health_water_id}",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:write"],
        )
    ],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_health_water(
    request: Request,
    health_water_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> None:
    """Delete a water intake record for the authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        health_water_id: ID of the water intake record.
        token_user_id: User ID from the access token.
        if_match: The ``If-Match`` precondition.
        db: Database session dependency.

    Raises:
        PreconditionFailedError: If the record changed since the client read it.
        NotFoundError: If the user has no such record.
    """
    health_water_service.delete_health_water(token_user_id, health_water_id, db, if_match=if_match)

edit_health_water

edit_health_water(request, health_water_id, health_water, token_user_id, db, response, if_match)

Edit an existing water intake record.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_water_id UuidId

ID of the record to change.

required
health_water HealthWaterUpdate

Water intake data to update.

required
token_user_id CurrentUserId

User ID from the access token.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
HealthWaterRead

Updated HealthWaterRead record.

Raises:

Type Description
NotFoundError

If the user has no such record.

PreconditionFailedError

If the record changed since the client read it.

Source code in backend/app/modules/health/health_water/router.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@router.patch(
    "/{health_water_id}",
    response_model=health_water_schema.HealthWaterRead,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:write"],
        )
    ],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_health_water(
    request: Request,
    health_water_id: core_dependencies.UuidId,
    health_water: health_water_schema.HealthWaterUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> health_water_schema.HealthWaterRead:
    """Edit an existing water intake record.

    Args:
        request: The incoming request, read by the rate limiter.
        health_water_id: ID of the record to change.
        health_water: Water intake data to update.
        token_user_id: User ID from the access token.
        db: Database session dependency.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        Updated HealthWaterRead record.

    Raises:
        NotFoundError: If the user has no such record.
        PreconditionFailedError: If the record changed since the client read it.
    """
    updated = health_water_service.edit_health_water(
        token_user_id, health_water_id, health_water, db, if_match=if_match
    )
    core_etag.set_etag(response, updated.version)
    return updated

read_health_water_all_pagination

read_health_water_all_pagination(token_user_id, db, page, date_range, interval=None)

Retrieve paginated water intake records for the user.

One page of records, newest first, optionally limited to an interval. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
page ListPage

The requested page and page size.

required
interval Annotated[Interval | None, Query(description='Look back from today over this interval; ignored when `start_date` or `end_date` is given')]

Optional interval looking back from today; ignored when a date range is given.

None
date_range DateRangeQuery

Optional inclusive start and end dates, which replace the interval.

required

Returns:

Type Description
Page[HealthWaterRead]

The page of records with the total matching the interval.

Source code in backend/app/modules/health/health_water/router.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@router.get(
    "",
    response_model=core_pagination.Page[health_water_schema.HealthWaterRead],
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:read"],
        )
    ],
)
def read_health_water_all_pagination(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    page: core_pagination.ListPage,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval | None,
        Query(description="Look back from today over this interval; ignored when `start_date` or `end_date` is given"),
    ] = None,
) -> core_pagination.Page[health_water_schema.HealthWaterRead]:
    """Retrieve paginated water intake records for the user.

    One page of records, newest first, optionally limited to an interval. Access is
    restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        page: The requested page and page size.
        interval: Optional interval looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates, which replace the interval.

    Returns:
        The page of records with the total matching the interval.
    """
    return health_water_service.list_health_water(
        token_user_id,
        db,
        page_number=page.page_number,
        num_records=page.num_records,
        interval=interval,
        date_range=date_range,
    )

read_health_water_by_id

read_health_water_by_id(health_water_id, token_user_id, db, response)

Retrieve one of the authenticated user's water records; its ETag is the version for If-Match.

Source code in backend/app/modules/health/health_water/router.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
@router.get(
    "/{health_water_id}",
    response_model=health_water_schema.HealthWaterRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_water_by_id(
    health_water_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_water_schema.HealthWaterRead:
    """Retrieve one of the authenticated user's water records; its ``ETag`` is the version for ``If-Match``."""
    record = health_water_service.get_health_water(token_user_id, health_water_id, db)
    core_etag.set_etag(response, record.version)
    return record

read_health_water_chart

read_health_water_chart(token_user_id, db, date_range, interval=health_constants.Interval.LAST_7_DAYS)

Chart the authenticated user's water intake over an interval.

One aggregated point per day, week or month depending on the interval, so the response stays small however long the history. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
interval Annotated[Interval, Query(description='Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given')]

The window to chart, looking back from today; ignored when a date range is given.

LAST_7_DAYS
date_range DateRangeQuery

Optional inclusive start and end dates to chart instead of the interval.

required

Returns:

Type Description
HealthChartSeries

The interval's bucket size and its points, oldest first.

Source code in backend/app/modules/health/health_water/router.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@router.get(
    "/chart",
    response_model=health_schema.HealthChartSeries,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_water_chart(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval,
        Query(
            description="Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given"
        ),
    ] = health_constants.Interval.LAST_7_DAYS,
) -> health_schema.HealthChartSeries:
    """Chart the authenticated user's water intake over an interval.

    One aggregated point per day, week or month depending on the interval, so the response stays small
    however long the history. Access is restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        interval: The window to chart, looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates to chart instead of the interval.

    Returns:
        The interval's bucket size and its points, oldest first.
    """
    return health_water_service.get_health_water_chart(token_user_id, interval, db, date_range=date_range)

Pydantic schemas for health water intake data.

This module defines the request/response schemas for water intake tracking, including validation rules and source enumeration.

HealthWaterBase

Bases: BaseModel

Base model for health water intake data.

Attributes:

Name Type Description
date date | None

Calendar date of the water intake record.

amount_ml date | None

Water consumed in milliliters.

Source code in backend/app/modules/health/health_water/schema.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class HealthWaterBase(BaseModel):
    """Base model for health water intake data.

    Attributes:
        date: Calendar date of the water intake record.
        amount_ml: Water consumed in milliliters.
    """

    date: datetime_date | None = Field(
        default=None,
        description="Calendar date of the water intake",
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

HealthWaterCreate

Bases: HealthWaterWrite

Schema for creating a new water intake record.

The date is optional; service fills it in when the client sends none.

Source code in backend/app/modules/health/health_water/schema.py
70
71
72
73
74
75
76
class HealthWaterCreate(HealthWaterWrite):
    """Schema for creating a new water intake record.

    The date is optional; ``service`` fills it in when the client sends none.
    """

    amount_ml: WaterAmountMl = Field(..., description="Water consumed in milliliters")

HealthWaterImport

Bases: HealthWaterCreate

Water record written by the server itself: a profile import.

Unlike :class:HealthWaterCreate it carries the provenance, which a client never sets. Every server-side writer of source takes Health<Kind>Import (create) or Health<Kind>ImportUpdate.

Attributes:

Name Type Description
source Source

The source the record came from; manual when none is given.

Source code in backend/app/modules/health/health_water/schema.py
118
119
120
121
122
123
124
125
126
127
128
class HealthWaterImport(HealthWaterCreate):
    """Water record written by the server itself: a profile import.

    Unlike :class:`HealthWaterCreate` it carries the provenance, which a client never sets. Every
    server-side writer of ``source`` takes ``Health<Kind>Import`` (create) or ``Health<Kind>ImportUpdate``.

    Attributes:
        source: The source the record came from; ``manual`` when none is given.
    """

    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the water intake data")

HealthWaterImportUpdate

Bases: HealthWaterUpdate

Fields a profile import changes on a water record, provenance included.

Attributes:

Name Type Description
source Source | None

The source the record came from.

Source code in backend/app/modules/health/health_water/schema.py
131
132
133
134
135
136
137
138
139
140
class HealthWaterImportUpdate(HealthWaterUpdate):
    """Fields a profile import changes on a water record, provenance included.

    Attributes:
        source: The source the record came from.
    """

    not_clearable: ClassVar[tuple[str, ...]] = (*HealthWaterUpdate.not_clearable, "source")

    source: Source | None = Field(default=None, description="Source of the water intake data")

HealthWaterRead

Bases: HealthWaterBase

Schema for reading a water intake record.

Attributes:

Name Type Description
source Source

Source of the water intake data.

id UUID

Unique identifier for the water intake record.

user_id UUID

Foreign key reference to the user.

Source code in backend/app/modules/health/health_water/schema.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class HealthWaterRead(HealthWaterBase):
    """Schema for reading a water intake record.

    Attributes:
        source: Source of the water intake data.
        id: Unique identifier for the water intake record.
        user_id: Foreign key reference to the user.
    """

    source: Source = Field(
        default=Source.MANUAL,
        validate_default=True,
        description="Source of the water intake data",
    )
    id: uuid.UUID = Field(
        ...,
        description=("Unique identifier for the water intake record"),
    )
    amount_ml: WaterAmountMl | None = Field(default=None, description="Water consumed in milliliters")
    user_id: uuid.UUID = Field(
        ...,
        description="Foreign key reference to the user",
    )
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    updated_at: datetime = Field(..., description="When the record last changed, set by the server")

HealthWaterUpdate

Bases: NotClearable, HealthWaterWrite

Schema for the fields a PATCH changes on a water record.

The record is named by the path, so the body carries neither an id nor an owner; only the fields present are changed.

Source code in backend/app/modules/health/health_water/schema.py
106
107
108
109
110
111
112
113
114
115
class HealthWaterUpdate(core_partial_update.NotClearable, HealthWaterWrite):
    """Schema for the fields a PATCH changes on a water record.

    The record is named by the path, so the body carries neither an id nor an owner; only the
    fields present are changed.
    """

    not_clearable: ClassVar[tuple[str, ...]] = ("date", "amount_ml")

    amount_ml: WaterAmountMl | None = Field(default=None, description="Water consumed in milliliters")

HealthWaterWrite

Bases: HealthWaterBase

Water fields a client writes: the date is bounded, which a stored row read back need not be.

Source code in backend/app/modules/health/health_water/schema.py
64
65
66
67
class HealthWaterWrite(HealthWaterBase):
    """Water fields a client writes: the date is bounded, which a stored row read back need not be."""

    date: core_types.RecordDate | None = Field(default=None, description="Calendar date of the water intake")

Source

Bases: StrEnum

Enumeration of data sources for water intake records.

Attributes:

Name Type Description
MANUAL

Manually entered water intake data.

GARMIN

Garmin fitness tracking platform as a data source.

Source code in backend/app/modules/health/health_water/schema.py
31
32
33
34
35
36
37
38
39
40
class Source(StrEnum):
    """Enumeration of data sources for water intake records.

    Attributes:
        MANUAL: Manually entered water intake data.
        GARMIN: Garmin fitness tracking platform as a data source.
    """

    MANUAL = "manual"
    GARMIN = "garmin"

Health weight

FastAPI router for health weight endpoints.

create_health_weight

create_health_weight(request, health_weight, token_user_id, db, response)

Create a health weight record for the authenticated user.

A date that already has a record is answered with a 409; change it with PATCH /{id}.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_weight HealthWeightCreate

The health weight data to create. Must include a date field.

required
token_user_id UUID

The ID of the authenticated user extracted from the access token.

required
db Session

Database session dependency for performing database operations.

required
response Response

The response, whose Location names where the record is read.

required

Returns:

Type Description
HealthWeightRead

health_weight_schema.HealthWeightRead: The created health weight record.

Source code in backend/app/modules/health/health_weight/router.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@router.post(
    "",
    response_model=health_weight_schema.HealthWeightRead,
    status_code=status.HTTP_201_CREATED,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def create_health_weight(
    request: Request,
    health_weight: health_weight_schema.HealthWeightCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_weight_schema.HealthWeightRead:
    """Create a health weight record for the authenticated user.

    A date that already has a record is answered with a 409; change it with ``PATCH /{id}``.

    Args:
        request: The incoming request, read by the rate limiter.
        health_weight (health_weight_schema.HealthWeightCreate): The health weight data to create.
            Must include a date field.
        token_user_id (uuid.UUID): The ID of the authenticated user extracted from the access token.
        db (Session): Database session dependency for performing database operations.
        response: The response, whose ``Location`` names where the record is read.

    Returns:
        health_weight_schema.HealthWeightRead: The created health weight record.

    """
    created = health_weight_service.create_health_weight(token_user_id, health_weight, db)
    core_location.set_location(response, request, "read_health_weight_by_id", health_weight_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_health_weight

delete_health_weight(request, health_weight_id, token_user_id, if_match, db)

Delete a health weight entry for the authenticated user.

This endpoint allows users to delete their own health weight records. It requires the 'health:write' scope for authorization.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_weight_id UUID

The unique identifier of the health weight entry to delete.

required
token_user_id UUID

The user ID extracted from the access token, used to ensure users can only delete their own weight entries.

required
if_match IfMatch

The If-Match precondition.

required
db Session

Database session dependency for performing database operations.

required

Returns:

Name Type Description
None None

This function does not return any value upon successful deletion.

Raises:

Type Description
PreconditionFailedError

If the record changed since the client read it.

NotFoundError

If the entry doesn't exist for the user.

Source code in backend/app/modules/health/health_weight/router.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@router.delete(
    "/{health_weight_id}",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_health_weight(
    request: Request,
    health_weight_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> None:
    """Delete a health weight entry for the authenticated user.

    This endpoint allows users to delete their own health weight records. It requires
    the 'health:write' scope for authorization.

    Args:
        request: The incoming request, read by the rate limiter.
        health_weight_id (uuid.UUID): The unique identifier of the health weight entry to delete.
        token_user_id (uuid.UUID): The user ID extracted from the access token, used to ensure
            users can only delete their own weight entries.
        if_match: The ``If-Match`` precondition.
        db (Session): Database session dependency for performing database operations.

    Returns:
        None: This function does not return any value upon successful deletion.

    Raises:
        PreconditionFailedError: If the record changed since the client read it.
        NotFoundError: If the entry doesn't exist for the user.
    """
    health_weight_service.delete_health_weight(token_user_id, health_weight_id, db, if_match=if_match)

edit_health_weight

edit_health_weight(request, health_weight_id, health_weight, token_user_id, db, response, if_match)

Edit a health weight entry for the authenticated user.

This endpoint allows users with 'health:write' scope to update an existing health weight record in the database.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_weight_id UuidId

ID of the record to change.

required
health_weight HealthWeight

The health weight data to be updated, containing the weight information and associated metadata.

required
token_user_id UUID

The ID of the authenticated user extracted from the access token.

required
db Session

Database session dependency for executing database operations.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
HealthWeightRead

The updated health weight record from the database.

Raises:

Type Description
PermissionDeniedError

If the record names another user.

NotFoundError

If the entry doesn't exist.

Source code in backend/app/modules/health/health_weight/router.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@router.patch(
    "/{health_weight_id}",
    response_model=health_weight_schema.HealthWeightRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:write"])],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_health_weight(
    request: Request,
    health_weight_id: core_dependencies.UuidId,
    health_weight: health_weight_schema.HealthWeightUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> health_weight_schema.HealthWeightRead:
    """Edit a health weight entry for the authenticated user.

    This endpoint allows users with 'health:write' scope to update an existing
    health weight record in the database.

    Args:
        request: The incoming request, read by the rate limiter.
        health_weight_id: ID of the record to change.
        health_weight (health_weight_schema.HealthWeight): The health weight data
            to be updated, containing the weight information and associated metadata.
        token_user_id (uuid.UUID): The ID of the authenticated user extracted from the
            access token.
        db (Session): Database session dependency for executing database operations.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        The updated health weight record from the database.

    Raises:
        PermissionDeniedError: If the record names another user.
        NotFoundError: If the entry doesn't exist.
    """
    updated = health_weight_service.edit_health_weight(
        token_user_id, health_weight_id, health_weight, db, if_match=if_match
    )
    core_etag.set_etag(response, updated.version)
    return updated

read_health_weight_all_pagination

read_health_weight_all_pagination(token_user_id, db, page, date_range, interval=None)

Retrieve paginated health weight records for the authenticated user.

One page of records, newest first, optionally limited to an interval. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
page ListPage

The requested page and page size.

required
interval Annotated[Interval | None, Query(description='Look back from today over this interval; ignored when `start_date` or `end_date` is given')]

Optional interval looking back from today; ignored when a date range is given.

None
date_range DateRangeQuery

Optional inclusive start and end dates, which replace the interval.

required

Returns:

Type Description
Page[HealthWeightRead]

The page of records with the total matching the interval.

Source code in backend/app/modules/health/health_weight/router.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@router.get(
    "",
    response_model=core_pagination.Page[health_weight_schema.HealthWeightRead],
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_weight_all_pagination(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    page: core_pagination.ListPage,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval | None,
        Query(description="Look back from today over this interval; ignored when `start_date` or `end_date` is given"),
    ] = None,
) -> core_pagination.Page[health_weight_schema.HealthWeightRead]:
    """Retrieve paginated health weight records for the authenticated user.

    One page of records, newest first, optionally limited to an interval. Access is
    restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        page: The requested page and page size.
        interval: Optional interval looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates, which replace the interval.

    Returns:
        The page of records with the total matching the interval.
    """
    return health_weight_service.list_health_weight(
        token_user_id,
        db,
        page_number=page.page_number,
        num_records=page.num_records,
        interval=interval,
        date_range=date_range,
    )

read_health_weight_by_id

read_health_weight_by_id(health_weight_id, token_user_id, db, response)

Retrieve one of the authenticated user's weight records; its ETag is the version for If-Match.

Source code in backend/app/modules/health/health_weight/router.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@router.get(
    "/{health_weight_id}",
    response_model=health_weight_schema.HealthWeightRead,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_weight_by_id(
    health_weight_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_weight_schema.HealthWeightRead:
    """Retrieve one of the authenticated user's weight records; its ``ETag`` is the version for ``If-Match``."""
    record = health_weight_service.get_health_weight(token_user_id, health_weight_id, db)
    core_etag.set_etag(response, record.version)
    return record

read_health_weight_chart

read_health_weight_chart(token_user_id, db, date_range, interval=health_constants.Interval.LAST_7_DAYS)

Chart the authenticated user's weight over an interval.

One aggregated point per day, week or month depending on the interval, so the response stays small however long the history. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
interval Annotated[Interval, Query(description='Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given')]

The window to chart, looking back from today; ignored when a date range is given.

LAST_7_DAYS
date_range DateRangeQuery

Optional inclusive start and end dates to chart instead of the interval.

required

Returns:

Type Description
HealthChartSeries

The interval's bucket size and its points, oldest first.

Source code in backend/app/modules/health/health_weight/router.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
@router.get(
    "/chart",
    response_model=health_schema.HealthChartSeries,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_weight_chart(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval,
        Query(
            description="Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given"
        ),
    ] = health_constants.Interval.LAST_7_DAYS,
) -> health_schema.HealthChartSeries:
    """Chart the authenticated user's weight over an interval.

    One aggregated point per day, week or month depending on the interval, so the response stays small
    however long the history. Access is restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        interval: The window to chart, looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates to chart instead of the interval.

    Returns:
        The interval's bucket size and its points, oldest first.
    """
    return health_weight_service.get_health_weight_chart(token_user_id, interval, db, date_range=date_range)

Pydantic request and response shapes for health weight records.

WeightKg module-attribute

WeightKg = Annotated[StrictFloat, Field(ge=0, le=500)]

Highest BMI a record may carry; a calculated value above it is unusable and not stored.

HealthWeightBase

Bases: BaseModel

Pydantic model for health weight data.

This model defines the structure and validation rules for health weight information, including body composition metrics and related health indicators.

Attributes:

Name Type Description
date date | None

The date of the health weight measurement.

weight_kg StrictFloat | None

Weight in kilograms. Must be between 0 and 500.

bmi StrictFloat | None

Body Mass Index value. Must be between 0 and 100.

body_fat_percent StrictFloat | None

Body fat percentage. Must be between 0 and 100.

body_water_percent StrictFloat | None

Body water percentage. Must be between 0 and 100.

bone_mass_kg StrictFloat | None

Bone mass in kilograms. Must be between 0 and 500.

muscle_mass_kg StrictFloat | None

Muscle mass in kilograms. Must be between 0 and 500.

physique_rating StrictInt | None

Physique rating score. Must be between 0 and the largest 32-bit integer.

visceral_fat StrictFloat | None

Visceral fat percentage. Must be between 0 and 100.

metabolic_age StrictInt | None

Metabolic age in years. Must be between 0 and 120.

Model Configuration
  • Populates from ORM attributes
  • Forbids extra fields
  • Validates assignments
  • Uses enum values for serialization
Source code in backend/app/modules/health/health_weight/schema.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class HealthWeightBase(BaseModel):
    """Pydantic model for health weight data.

    This model defines the structure and validation rules for health weight information,
    including body composition metrics and related health indicators.

    Attributes:
        date (datetime_date | None): The date of the health weight measurement.
        weight_kg (StrictFloat | None): Weight in kilograms. Must be between 0 and 500.
        bmi (StrictFloat | None): Body Mass Index value. Must be between 0 and 100.
        body_fat_percent (StrictFloat | None): Body fat percentage. Must be between 0 and 100.
        body_water_percent (StrictFloat | None): Body water percentage. Must be between 0 and 100.
        bone_mass_kg (StrictFloat | None): Bone mass in kilograms. Must be between 0 and 500.
        muscle_mass_kg (StrictFloat | None): Muscle mass in kilograms. Must be between 0 and 500.
        physique_rating (StrictInt | None): Physique rating score. Must be between 0 and the largest 32-bit integer.
        visceral_fat (StrictFloat | None): Visceral fat percentage. Must be between 0 and 100.
        metabolic_age (StrictInt | None): Metabolic age in years. Must be between 0 and 120.

    Model Configuration:
        - Populates from ORM attributes
        - Forbids extra fields
        - Validates assignments
        - Uses enum values for serialization
    """

    date: datetime_date | None = Field(default=None, description="Health weight date (date)")
    bmi: StrictFloat | None = Field(
        default=None,
        ge=0,
        le=MAX_BMI,
        description=(
            "Body Mass Index; a manually entered record ignores a value sent and derives it from the weight and height"
        ),
    )
    body_fat_percent: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Body fat as a percentage of body weight (0-100)"
    )
    body_water_percent: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Body water as a percentage of body weight (0-100)"
    )
    bone_mass_kg: StrictFloat | None = Field(default=None, ge=0, le=500, description="Bone mass in kilograms")
    muscle_mass_kg: StrictFloat | None = Field(default=None, ge=0, le=500, description="Muscle mass in kilograms")
    physique_rating: StrictInt | None = Field(
        default=None, ge=0, le=core_types.INT32_MAX, description="Physique rating, a score (not a unit)"
    )
    visceral_fat: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Visceral fat rating (a score, not a unit)"
    )
    metabolic_age: StrictInt | None = Field(default=None, ge=0, le=120, description="Metabolic age in years")

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

HealthWeightCreate

Bases: HealthWeightWrite

Schema for creating a health weight record.

The date is optional; service fills it in when the client sends none.

Source code in backend/app/modules/health/health_weight/schema.py
103
104
105
106
107
108
109
class HealthWeightCreate(HealthWeightWrite):
    """Schema for creating a health weight record.

    The date is optional; ``service`` fills it in when the client sends none.
    """

    weight_kg: WeightKg = Field(..., description="Weight in kilograms")

HealthWeightImport

Bases: HealthWeightCreate

Weight record written by the server itself: a provider sync or a profile import.

Unlike :class:HealthWeightCreate it carries the provenance, which a client never sets. Every server-side writer of source takes Health<Kind>Import (create) or Health<Kind>ImportUpdate.

Attributes:

Name Type Description
source Source

The source the record came from; manual when none is given.

Source code in backend/app/modules/health/health_weight/schema.py
144
145
146
147
148
149
150
151
152
153
154
class HealthWeightImport(HealthWeightCreate):
    """Weight record written by the server itself: a provider sync or a profile import.

    Unlike :class:`HealthWeightCreate` it carries the provenance, which a client never sets. Every
    server-side writer of ``source`` takes ``Health<Kind>Import`` (create) or ``Health<Kind>ImportUpdate``.

    Attributes:
        source (Source): The source the record came from; ``manual`` when none is given.
    """

    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the weight data")

HealthWeightImportUpdate

Bases: HealthWeightUpdate

Fields a provider sync or a profile import changes on a weight record, provenance included.

Attributes:

Name Type Description
source Source | None

The source the record came from.

Source code in backend/app/modules/health/health_weight/schema.py
157
158
159
160
161
162
163
164
165
166
class HealthWeightImportUpdate(HealthWeightUpdate):
    """Fields a provider sync or a profile import changes on a weight record, provenance included.

    Attributes:
        source (Source | None): The source the record came from.
    """

    not_clearable: ClassVar[tuple[str, ...]] = (*HealthWeightUpdate.not_clearable, "source")

    source: Source | None = Field(default=None, description="Source of the weight data")

HealthWeightRead

Bases: HealthWeightBase

Schema for reading a health weight record.

Extends HealthWeightBase with identifier fields required for retrieving and referencing weight records in the system.

Attributes:

Name Type Description
source Source | None

The source or device from which the weight data was obtained.

id UUID

Unique identifier for the weight record to update.

user_id UUID

Foreign key reference to the user.

Source code in backend/app/modules/health/health_weight/schema.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class HealthWeightRead(HealthWeightBase):
    """Schema for reading a health weight record.

    Extends HealthWeightBase with identifier fields required for retrieving
    and referencing weight records in the system.

    Attributes:
        source (Source | None): The source or device from which the weight data was obtained.
        id (uuid.UUID): Unique identifier for the weight record to update.
        user_id (uuid.UUID): Foreign key reference to the user.
    """

    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the weight data")
    id: uuid.UUID = Field(..., description="Unique identifier for the weight record to update")
    weight_kg: WeightKg | None = Field(default=None, description="Weight in kilograms")
    user_id: uuid.UUID = Field(..., description="Foreign key reference to the user")
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    updated_at: datetime = Field(..., description="When the record last changed, set by the server")

HealthWeightUpdate

Bases: NotClearable, HealthWeightWrite

Schema for the fields a PATCH changes on a weight record.

The record is named by the path, so the body carries neither an id nor an owner; only the fields present are changed.

Source code in backend/app/modules/health/health_weight/schema.py
132
133
134
135
136
137
138
139
140
141
class HealthWeightUpdate(core_partial_update.NotClearable, HealthWeightWrite):
    """Schema for the fields a PATCH changes on a weight record.

    The record is named by the path, so the body carries neither an id nor an owner; only the
    fields present are changed.
    """

    not_clearable: ClassVar[tuple[str, ...]] = ("date", "weight_kg")

    weight_kg: WeightKg | None = Field(default=None, description="Weight in kilograms")

HealthWeightWrite

Bases: HealthWeightBase

Weight fields a client writes: the date is bounded, which a stored row read back need not be.

Source code in backend/app/modules/health/health_weight/schema.py
 97
 98
 99
100
class HealthWeightWrite(HealthWeightBase):
    """Weight fields a client writes: the date is bounded, which a stored row read back need not be."""

    date: core_types.RecordDate | None = Field(default=None, description="Health weight date (date)")

Source

Bases: Enum

Enumeration of data sources for health weight records.

Attributes:

Name Type Description
MANUAL

Manually entered data.

GARMIN

Garmin fitness tracking platform as a data source.

Source code in backend/app/modules/health/health_weight/schema.py
27
28
29
30
31
32
33
34
35
36
class Source(Enum):
    """Enumeration of data sources for health weight records.

    Attributes:
        MANUAL: Manually entered data.
        GARMIN: Garmin fitness tracking platform as a data source.
    """

    MANUAL = "manual"
    GARMIN = "garmin"

Health poop

FastAPI router for health poop (bowel movement) endpoints.

This module defines the API endpoints for managing bowel movement records, including CRUD operations with pagination and filtering.

create_health_poop

create_health_poop(request, health_poop, token_user_id, db, response)

Create a new poop record for the user.

Unlike other health modules, multiple poop records can exist per day.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_poop HealthPoopCreate

Poop data to create.

required
token_user_id CurrentUserId

User ID from the access token.

required
db DbSession

Database session dependency.

required
response Response

The response, whose Location names where the record is read.

required

Returns:

Type Description
HealthPoopRead

Created HealthPoopRead record.

Source code in backend/app/modules/health/health_poop/router.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
@router.post(
    "",
    response_model=health_poop_schema.HealthPoopRead,
    status_code=status.HTTP_201_CREATED,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:write"],
        )
    ],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def create_health_poop(
    request: Request,
    health_poop: health_poop_schema.HealthPoopCreate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_poop_schema.HealthPoopRead:
    """Create a new poop record for the user.

    Unlike other health modules, multiple poop records can exist
    per day.

    Args:
        request: The incoming request, read by the rate limiter.
        health_poop: Poop data to create.
        token_user_id: User ID from the access token.
        db: Database session dependency.
        response: The response, whose ``Location`` names where the record is read.

    Returns:
        Created HealthPoopRead record.
    """
    created = health_poop_service.create_health_poop(token_user_id, health_poop, db)
    core_location.set_location(response, request, "read_health_poop_by_id", health_poop_id=created.id)
    core_etag.set_etag(response, created.version)
    return created

delete_health_poop

delete_health_poop(request, health_poop_id, token_user_id, if_match, db)

Delete a poop record for the authenticated user.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_poop_id UuidId

ID of the poop record to delete.

required
token_user_id CurrentUserId

User ID from the access token.

required
if_match IfMatch

The If-Match precondition.

required
db DbSession

Database session dependency.

required

Raises:

Type Description
PreconditionFailedError

If the record changed since the client read it.

NotFoundError

If the user has no such record.

Source code in backend/app/modules/health/health_poop/router.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
@router.delete(
    "/{health_poop_id}",
    response_model=None,
    status_code=status.HTTP_204_NO_CONTENT,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:write"],
        )
    ],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def delete_health_poop(
    request: Request,
    health_poop_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    if_match: core_dependencies.IfMatch,
    db: core_dependencies.DbSession,
) -> None:
    """Delete a poop record for the authenticated user.

    Args:
        request: The incoming request, read by the rate limiter.
        health_poop_id: ID of the poop record to delete.
        token_user_id: User ID from the access token.
        if_match: The ``If-Match`` precondition.
        db: Database session dependency.

    Raises:
        PreconditionFailedError: If the record changed since the client read it.
        NotFoundError: If the user has no such record.
    """
    health_poop_service.delete_health_poop(token_user_id, health_poop_id, db, if_match=if_match)

edit_health_poop

edit_health_poop(request, health_poop_id, health_poop, token_user_id, db, response, if_match)

Edit an existing poop record.

Parameters:

Name Type Description Default
request Request

The incoming request, read by the rate limiter.

required
health_poop_id UuidId

ID of the record to change.

required
health_poop HealthPoopUpdate

Poop data to update.

required
token_user_id CurrentUserId

User ID from the access token.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the new ETag.

required
if_match IfMatch

The If-Match precondition.

required

Returns:

Type Description
HealthPoopRead

Updated HealthPoopRead record.

Raises:

Type Description
NotFoundError

If the user has no such record.

PreconditionFailedError

If the record changed since the client read it.

Source code in backend/app/modules/health/health_poop/router.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
@router.patch(
    "/{health_poop_id}",
    response_model=health_poop_schema.HealthPoopRead,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:write"],
        )
    ],
)
@core_rate_limit.limiter.limit(core_rate_limit.WRITE)
def edit_health_poop(
    request: Request,
    health_poop_id: core_dependencies.UuidId,
    health_poop: health_poop_schema.HealthPoopUpdate,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
    if_match: core_dependencies.IfMatch,
) -> health_poop_schema.HealthPoopRead:
    """Edit an existing poop record.

    Args:
        request: The incoming request, read by the rate limiter.
        health_poop_id: ID of the record to change.
        health_poop: Poop data to update.
        token_user_id: User ID from the access token.
        db: Database session dependency.
        response: The response, which carries the new ETag.
        if_match: The ``If-Match`` precondition.

    Returns:
        Updated HealthPoopRead record.

    Raises:
        NotFoundError: If the user has no such record.
        PreconditionFailedError: If the record changed since the client read it.
    """
    updated = health_poop_service.edit_health_poop(token_user_id, health_poop_id, health_poop, db, if_match=if_match)
    core_etag.set_etag(response, updated.version)
    return updated

read_health_poop_all_pagination

read_health_poop_all_pagination(token_user_id, db, page, date_range, interval=None)

Retrieve paginated poop records for the user.

One page of records, newest first, optionally limited to an interval. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
page ListPage

The requested page and page size.

required
interval Annotated[Interval | None, Query(description='Look back from today over this interval; ignored when `start_date` or `end_date` is given')]

Optional interval looking back from today; ignored when a date range is given.

None
date_range DateRangeQuery

Optional inclusive start and end dates, which replace the interval.

required

Returns:

Type Description
Page[HealthPoopRead]

The page of records with the total matching the interval.

Source code in backend/app/modules/health/health_poop/router.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@router.get(
    "",
    response_model=core_pagination.Page[health_poop_schema.HealthPoopRead],
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:read"],
        )
    ],
)
def read_health_poop_all_pagination(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    page: core_pagination.ListPage,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval | None,
        Query(description="Look back from today over this interval; ignored when `start_date` or `end_date` is given"),
    ] = None,
) -> core_pagination.Page[health_poop_schema.HealthPoopRead]:
    """Retrieve paginated poop records for the user.

    One page of records, newest first, optionally limited to an interval. Access is
    restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        page: The requested page and page size.
        interval: Optional interval looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates, which replace the interval.

    Returns:
        The page of records with the total matching the interval.
    """
    return health_poop_service.list_health_poop(
        token_user_id,
        db,
        page_number=page.page_number,
        num_records=page.num_records,
        interval=interval,
        date_range=date_range,
    )

read_health_poop_by_id

read_health_poop_by_id(health_poop_id, token_user_id, db, response)

Retrieve a specific poop record by ID.

Parameters:

Name Type Description Default
health_poop_id UuidId

ID of the poop record.

required
token_user_id CurrentUserId

User ID from the access token.

required
db DbSession

Database session dependency.

required
response Response

The response, which carries the record's ETag.

required

Returns:

Type Description
HealthPoopRead

HealthPoopRead for the specified record.

Raises:

Type Description
NotFoundError

If the user has no such record.

Source code in backend/app/modules/health/health_poop/router.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
@router.get(
    "/{health_poop_id}",
    response_model=health_poop_schema.HealthPoopRead,
    dependencies=[
        Security(
            auth_dependencies.check_scopes,
            scopes=["health:read"],
        )
    ],
)
def read_health_poop_by_id(
    health_poop_id: core_dependencies.UuidId,
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    response: Response,
) -> health_poop_schema.HealthPoopRead:
    """Retrieve a specific poop record by ID.

    Args:
        health_poop_id: ID of the poop record.
        token_user_id: User ID from the access token.
        db: Database session dependency.
        response: The response, which carries the record's ETag.

    Returns:
        HealthPoopRead for the specified record.

    Raises:
        NotFoundError: If the user has no such record.
    """
    record = health_poop_service.get_health_poop(token_user_id, health_poop_id, db)
    core_etag.set_etag(response, record.version)
    return record

read_health_poop_chart

read_health_poop_chart(token_user_id, db, date_range, interval=health_constants.Interval.LAST_7_DAYS)

Chart the authenticated user's daily bowel-movement frequency over an interval.

One aggregated point per day, week or month depending on the interval, so the response stays small however long the history. Declared before the /{health_poop_id} route so chart is not read as an id. Access is restricted to users with the 'health:read' scope.

Parameters:

Name Type Description Default
token_user_id CurrentUserId

The ID of the authenticated user extracted from the access token.

required
db DbSession

Database session for executing queries.

required
interval Annotated[Interval, Query(description='Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given')]

The window to chart, looking back from today; ignored when a date range is given.

LAST_7_DAYS
date_range DateRangeQuery

Optional inclusive start and end dates to chart instead of the interval.

required

Returns:

Type Description
HealthChartSeries

The interval's bucket size and its points, oldest first.

Source code in backend/app/modules/health/health_poop/router.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@router.get(
    "/chart",
    response_model=health_schema.HealthChartSeries,
    dependencies=[Security(auth_dependencies.check_scopes, scopes=["health:read"])],
)
def read_health_poop_chart(
    token_user_id: auth_dependencies.CurrentUserId,
    db: core_dependencies.DbSession,
    date_range: core_date_range.DateRangeQuery,
    interval: Annotated[
        health_constants.Interval,
        Query(
            description="Interval to chart, looking back from today; ignored when `start_date` or `end_date` is given"
        ),
    ] = health_constants.Interval.LAST_7_DAYS,
) -> health_schema.HealthChartSeries:
    """Chart the authenticated user's daily bowel-movement frequency over an interval.

    One aggregated point per day, week or month depending on the interval, so the response stays small
    however long the history. Declared before the ``/{health_poop_id}`` route so ``chart`` is not read as an id.
    Access is restricted to users with the 'health:read' scope.

    Args:
        token_user_id: The ID of the authenticated user extracted from the access token.
        db: Database session for executing queries.
        interval: The window to chart, looking back from today; ignored when a date range is given.
        date_range: Optional inclusive start and end dates to chart instead of the interval.

    Returns:
        The interval's bucket size and its points, oldest first.
    """
    return health_poop_service.get_health_poop_chart(token_user_id, interval, db, date_range=date_range)

Pydantic schemas for health poop (bowel movement) data.

This module defines the request/response schemas for bowel movement tracking, including validation rules, Bristol Stool Scale types, and color enumerations.

BristolType

Bases: StoredStrEnum

Bristol Stool Scale classification types; stored is the scale number kept in the database.

Attributes:

Name Type Description
TYPE_1

Separate hard lumps (severe constipation).

TYPE_2

Lumpy and sausage-like (mild constipation).

TYPE_3

Sausage shape with cracks (normal).

TYPE_4

Smooth, soft sausage (normal, ideal).

TYPE_5

Soft blobs with clear edges (lacking fiber).

TYPE_6

Mushy with ragged edges (mild diarrhea).

TYPE_7

Liquid, no solid pieces (severe diarrhea).

Source code in backend/app/modules/health/health_poop/schema.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class BristolType(StoredStrEnum):
    """Bristol Stool Scale classification types; ``stored`` is the scale number kept in the database.

    Attributes:
        TYPE_1: Separate hard lumps (severe constipation).
        TYPE_2: Lumpy and sausage-like (mild constipation).
        TYPE_3: Sausage shape with cracks (normal).
        TYPE_4: Smooth, soft sausage (normal, ideal).
        TYPE_5: Soft blobs with clear edges (lacking fiber).
        TYPE_6: Mushy with ragged edges (mild diarrhea).
        TYPE_7: Liquid, no solid pieces (severe diarrhea).
    """

    TYPE_1 = ("type_1", 1)
    TYPE_2 = ("type_2", 2)
    TYPE_3 = ("type_3", 3)
    TYPE_4 = ("type_4", 4)
    TYPE_5 = ("type_5", 5)
    TYPE_6 = ("type_6", 6)
    TYPE_7 = ("type_7", 7)

Color

Bases: Enum

Enumeration of common stool color descriptions.

Attributes:

Name Type Description
BROWN

Normal brown color.

DARK_BROWN

Darker than normal brown.

LIGHT_BROWN

Lighter than normal brown.

YELLOW

Yellowish color.

GREEN

Greenish color.

BLACK

Black or very dark color.

RED

Red or reddish color.

WHITE

White or clay-colored.

Source code in backend/app/modules/health/health_poop/schema.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Color(Enum):
    """Enumeration of common stool color descriptions.

    Attributes:
        BROWN: Normal brown color.
        DARK_BROWN: Darker than normal brown.
        LIGHT_BROWN: Lighter than normal brown.
        YELLOW: Yellowish color.
        GREEN: Greenish color.
        BLACK: Black or very dark color.
        RED: Red or reddish color.
        WHITE: White or clay-colored.
    """

    BROWN = "brown"
    DARK_BROWN = "dark_brown"
    LIGHT_BROWN = "light_brown"
    YELLOW = "yellow"
    GREEN = "green"
    BLACK = "black"
    RED = "red"
    WHITE = "white"

HealthPoopBase

Bases: BaseModel

Base model for health poop data.

Attributes:

Name Type Description
date_time

Date and time of the bowel movement.

bristol_type StoredBristolType | None

Bristol Stool Scale type.

color Color | None

Stool color description.

notes StrictStr | None

Optional notes about the bowel movement.

Source code in backend/app/modules/health/health_poop/schema.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class HealthPoopBase(BaseModel):
    """Base model for health poop data.

    Attributes:
        date_time: Date and time of the bowel movement.
        bristol_type: Bristol Stool Scale type.
        color: Stool color description.
        notes: Optional notes about the bowel movement.
    """

    bristol_type: StoredBristolType | None = Field(
        default=None,
        description="Bristol Stool Scale type",
    )
    color: Color | None = Field(
        default=None,
        description="Stool color description",
    )
    notes: StrictStr | None = Field(
        default=None,
        max_length=500,
        description=("Optional notes about the bowel movement"),
    )

    model_config = ConfigDict(
        from_attributes=True,
        extra="forbid",
        validate_assignment=True,
        use_enum_values=True,
    )

HealthPoopCreate

Bases: HealthPoopWrite

Schema for creating a new poop record.

Requires date_time.

Source code in backend/app/modules/health/health_poop/schema.py
134
135
136
137
138
139
140
141
142
143
class HealthPoopCreate(HealthPoopWrite):
    """Schema for creating a new poop record.

    Requires date_time.
    """

    date_time: core_types.RecordInstant = Field(
        ...,
        description="Date and time of the bowel movement, with a UTC offset",
    )

HealthPoopImport

Bases: HealthPoopCreate

Poop record written by the server itself: a profile import, or a client's record with its assigned source.

Unlike :class:HealthPoopCreate it carries the provenance, which a client never sets. Every server-side writer of source takes Health<Kind>Import (create) or Health<Kind>ImportUpdate. A record without a source is a manual one.

Attributes:

Name Type Description
source Source

The source the record came from; manual when none is given.

Source code in backend/app/modules/health/health_poop/schema.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class HealthPoopImport(HealthPoopCreate):
    """Poop record written by the server itself: a profile import, or a client's record with its assigned source.

    Unlike :class:`HealthPoopCreate` it carries the provenance, which a client never sets. Every
    server-side writer of ``source`` takes ``Health<Kind>Import`` (create) or ``Health<Kind>ImportUpdate``. A record
    without a source is a manual one.

    Attributes:
        source: The source the record came from; ``manual`` when none is given.
    """

    bristol_type: StoredBristolType | None = Field(
        default=None,
        description="Bristol Stool Scale type",
    )
    source: Source = Field(default=Source.MANUAL, validate_default=True, description="Source of the data")
    date_time: core_types.ImportedInstant = Field(..., description="Date and time of the bowel movement")

HealthPoopRead

Bases: HealthPoopBase

Schema for reading a poop record.

Attributes:

Name Type Description
source Source

Source of the data.

id UUID

Unique identifier for the poop record.

user_id UUID

Foreign key reference to the user.

Source code in backend/app/modules/health/health_poop/schema.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class HealthPoopRead(HealthPoopBase):
    """Schema for reading a poop record.

    Attributes:
        source: Source of the data.
        id: Unique identifier for the poop record.
        user_id: Foreign key reference to the user.
    """

    source: Source = Field(
        default=Source.MANUAL,
        validate_default=True,
        description="Source of the data",
    )
    id: uuid.UUID = Field(
        ...,
        description=("Unique identifier for the poop record"),
    )
    date_time: datetime = Field(
        ...,
        description="Date and time of the bowel movement",
    )
    user_id: uuid.UUID = Field(
        ...,
        description="Foreign key reference to the user",
    )
    version: StrictInt = Field(default=1, ge=1, description="Optimistic-concurrency counter, also sent as the ETag")
    updated_at: datetime = Field(..., description="When the record last changed, set by the server")

HealthPoopUpdate

Bases: NotClearable, HealthPoopWrite

Schema for the fields a PATCH changes on a poop record.

The record is named by the path, so the body carries neither an id nor an owner; only the fields present are changed.

Source code in backend/app/modules/health/health_poop/schema.py
176
177
178
179
180
181
182
183
184
185
186
187
188
class HealthPoopUpdate(core_partial_update.NotClearable, HealthPoopWrite):
    """Schema for the fields a PATCH changes on a poop record.

    The record is named by the path, so the body carries neither an id nor an owner; only the
    fields present are changed.
    """

    not_clearable = ("date_time",)

    date_time: core_types.RecordInstant | None = Field(
        default=None,
        description="Date and time of the bowel movement, with a UTC offset",
    )

HealthPoopWrite

Bases: HealthPoopBase

Poop fields a client writes: the time is bounded, which a stored row read back need not be.

Source code in backend/app/modules/health/health_poop/schema.py
125
126
127
128
129
130
131
class HealthPoopWrite(HealthPoopBase):
    """Poop fields a client writes: the time is bounded, which a stored row read back need not be."""

    bristol_type: _BristolTypeMember | None = Field(
        default=None,
        description="Bristol Stool Scale type",
    )

Source

Bases: Enum

Enumeration of data sources for poop records.

Attributes:

Name Type Description
MANUAL

Manually entered data.

Source code in backend/app/modules/health/health_poop/schema.py
28
29
30
31
32
33
34
35
class Source(Enum):
    """Enumeration of data sources for poop records.

    Attributes:
        MANUAL: Manually entered data.
    """

    MANUAL = "manual"