Skip to content

API Reference

Health weight module for managing user weight and body composition.

This module provides CRUD operations and data models for user weight tracking including BMI, body composition metrics, and various health indicators.

Exports
  • CRUD: get_all_health_weight, get_health_weight_number, get_all_health_weight_by_user_id, get_health_weight_by_id_and_user_id, get_health_weight_with_pagination, get_health_weight_by_date, create_health_weight, edit_health_weight, delete_health_weight
  • Schemas: HealthWeightBase, HealthWeightCreate, HealthWeightUpdate, HealthWeightRead, HealthWeightListResponse
  • Enums: Source
  • Models: HealthWeight (ORM model)
  • Utils: calculate_bmi, calculate_bmi_all_user_entries

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 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 StrictFloat | None

Body fat percentage. Must be between 0 and 100.

body_water StrictFloat | None

Body water percentage. Must be between 0 and 100.

bone_mass StrictFloat | None

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

muscle_mass StrictFloat | None

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

physique_rating StrictInt | None

Physique rating score. Must be greater than or equal to 0.

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.

source Source | None

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

Model Configuration
  • Populates from ORM attributes
  • Forbids extra fields
  • Validates assignments
  • Uses enum values for serialization
Source code in backend/app/health/health_weight/schema.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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 (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 (StrictFloat | None): Body fat percentage. Must be between 0 and 100.
        body_water (StrictFloat | None): Body water percentage. Must be between 0 and 100.
        bone_mass (StrictFloat | None): Bone mass in kilograms. Must be between 0 and 500.
        muscle_mass (StrictFloat | None): Muscle mass in kilograms. Must be between 0 and 500.
        physique_rating (StrictInt | None): Physique rating score. Must be greater than or equal to 0.
        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.
        source (Source | None): The source or device from which the weight data was obtained.

    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)"
    )
    weight: StrictFloat | None = Field(
        default=None, ge=0, le=500, description="Weight in kilograms"
    )
    bmi: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Body Mass Index"
    )
    body_fat: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Body fat percentage"
    )
    body_water: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Body water percentage"
    )
    bone_mass: StrictFloat | None = Field(
        default=None, ge=0, le=500, description="Bone mass in kilograms"
    )
    muscle_mass: StrictFloat | None = Field(
        default=None, ge=0, le=500, description="Muscle mass in kilograms"
    )
    physique_rating: StrictInt | None = Field(
        default=None, ge=0, description="Physique rating"
    )
    visceral_fat: StrictFloat | None = Field(
        default=None, ge=0, le=100, description="Visceral fat"
    )
    metabolic_age: StrictInt | None = Field(
        default=None, ge=0, le=120, description="Metabolic age"
    )
    source: Source | None = Field(default=None, description="Source of the weight data")

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

HealthWeightCreate

Bases: HealthWeightBase

Validator for HealthWeightCreate model that automatically sets the date field.

This validator runs after model initialization to ensure that if no date is provided, it defaults to today's date.

Source code in backend/app/health/health_weight/schema.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class HealthWeightCreate(HealthWeightBase):
    """
    Validator for HealthWeightCreate model that automatically sets the date field.

    This validator runs after model initialization to ensure that if no date
    is provided, it defaults to today's date.
    """

    @model_validator(mode="after")
    def set_default_date(self) -> "HealthWeightCreate":
        """
        Set date to today if not provided.

        Returns:
            The validated model instance with date set.
        """
        if self.date is None:
            self.date = datetime_date.today()
        return self

set_default_date

set_default_date()

Set date to today if not provided.

Returns:

Type Description
HealthWeightCreate

The validated model instance with date set.

Source code in backend/app/health/health_weight/schema.py
 99
100
101
102
103
104
105
106
107
108
109
@model_validator(mode="after")
def set_default_date(self) -> "HealthWeightCreate":
    """
    Set date to today if not provided.

    Returns:
        The validated model instance with date set.
    """
    if self.date is None:
        self.date = datetime_date.today()
    return self

HealthWeightListResponse

Bases: BaseModel

Response model for listing health weight records.

Attributes:

Name Type Description
total StrictInt

Total number of weight records for the user.

num_records StrictInt | None

Number of records in this response.

page_number StrictInt | None

Current page number.

records list[HealthWeightRead]

List of health weight records.

Source code in backend/app/health/health_weight/schema.py
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
167
168
class HealthWeightListResponse(BaseModel):
    """
    Response model for listing health weight records.

    Attributes:
        total (StrictInt): Total number of weight records for the user.
        num_records (StrictInt | None): Number of records in this response.
        page_number (StrictInt | None): Current page number.
        records (list[HealthWeightRead]): List of health weight records.
    """

    total: StrictInt = Field(
        ..., description="Total number of weight records for the user"
    )
    num_records: StrictInt | None = Field(
        default=None, description="Number of records in this response"
    )
    page_number: StrictInt | None = Field(
        default=None, description="Current page number"
    )
    records: list[HealthWeightRead] = Field(
        ..., description="List of health weight records"
    )

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

HealthWeightModel

Bases: Base

User health weight and body composition data.

Attributes:

Name Type Description
id Mapped[int]

Primary key.

user_id Mapped[int]

Foreign key to users table.

date Mapped[date]

Calendar date of the measurement.

weight Mapped[Decimal]

Weight in kilograms.

bmi Mapped[Decimal | None]

Body Mass Index.

body_fat Mapped[Decimal | None]

Body fat percentage.

body_water Mapped[Decimal | None]

Body hydration percentage.

bone_mass Mapped[Decimal | None]

Bone mass percentage.

muscle_mass Mapped[Decimal | None]

Muscle mass percentage.

physique_rating Mapped[int | None]

Physique rating score.

visceral_fat Mapped[Decimal | None]

Visceral fat rating.

metabolic_age Mapped[int | None]

Calculated metabolic age.

source Mapped[str | None]

Data source.

user Mapped[str | None]

Relationship to Users model.

Source code in backend/app/health/health_weight/models.py
 8
 9
10
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
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
95
96
97
class HealthWeight(Base):
    """
    User health weight and body composition data.

    Attributes:
        id: Primary key.
        user_id: Foreign key to users table.
        date: Calendar date of the measurement.
        weight: Weight in kilograms.
        bmi: Body Mass Index.
        body_fat: Body fat percentage.
        body_water: Body hydration percentage.
        bone_mass: Bone mass percentage.
        muscle_mass: Muscle mass percentage.
        physique_rating: Physique rating score.
        visceral_fat: Visceral fat rating.
        metabolic_age: Calculated metabolic age.
        source: Data source.
        user: Relationship to Users model.
    """

    __tablename__ = "health_weight"

    id: Mapped[int] = mapped_column(
        primary_key=True,
        autoincrement=True,
    )
    user_id: Mapped[int] = mapped_column(
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
        comment="User ID that the health_weight belongs",
    )
    date: Mapped[date_type] = mapped_column(
        nullable=False,
        index=True,
        comment="Health weight date (date)",
    )
    weight: Mapped[Decimal] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=False,
        comment="Weight in kg",
    )
    bmi: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Body mass index (BMI)",
    )
    body_fat: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Body fat percentage",
    )
    body_water: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Body hydration percentage",
    )
    bone_mass: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Bone mass percentage",
    )
    muscle_mass: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Muscle mass percentage",
    )
    physique_rating: Mapped[int | None] = mapped_column(
        nullable=True,
        comment="Physique rating",
    )
    visceral_fat: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Visceral fat rating",
    )
    metabolic_age: Mapped[int | None] = mapped_column(
        nullable=True,
        comment="Metabolic age",
    )
    source: Mapped[str | None] = mapped_column(
        String(250),
        nullable=True,
        comment="Source of the health weight data",
    )

    # Define a relationship to the Users model
    # TODO: Change to Mapped["User"] when all modules use mapped
    users = relationship("Users", back_populates="health_weight")

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
id StrictInt

Unique identifier for the weight record to update.

user_id StrictInt

Foreign key reference to the user.

Source code in backend/app/health/health_weight/schema.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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:
        id (StrictInt): Unique identifier for the weight record to update.
        user_id (StrictInt): Foreign key reference to the user.
    """

    id: StrictInt = Field(
        ..., description="Unique identifier for the weight record to update"
    )
    user_id: StrictInt = Field(..., description="Foreign key reference to the user")

HealthWeightUpdate

Bases: HealthWeightRead

Schema for updating health weight records.

Inherits from HealthWeightRead to maintain consistency with read operations while allowing modifications to health weight data. This schema is used for PUT/PATCH requests to update existing health weight entries.

Source code in backend/app/health/health_weight/schema.py
130
131
132
133
134
135
136
137
class HealthWeightUpdate(HealthWeightRead):
    """
    Schema for updating health weight records.

    Inherits from HealthWeightRead to maintain consistency with read operations
    while allowing modifications to health weight data. This schema is used for
    PUT/PATCH requests to update existing health weight entries.
    """

Source

Bases: Enum

Enumeration of data sources for health weight records.

Attributes:

Name Type Description
GARMIN

Garmin fitness tracking platform as a data source.

Source code in backend/app/health/health_weight/schema.py
13
14
15
16
17
18
19
20
21
class Source(Enum):
    """
    Enumeration of data sources for health weight records.

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

    GARMIN = "garmin"

calculate_bmi

calculate_bmi(health_weight, user_id, db)

Calculate the Body Mass Index (BMI) for a health weight record.

Parameters:

Name Type Description Default
health_weight HealthWeightCreate | HealthWeightUpdate

Health weight record with weight value.

required
user_id int

Unique identifier of the user.

required
db Session

Database session.

required

Returns:

Type Description
HealthWeightCreate | HealthWeightUpdate

Updated health weight record with calculated BMI.

Source code in backend/app/health/health_weight/utils.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
def calculate_bmi(
    health_weight: (
        health_weight_schema.HealthWeightCreate
        | health_weight_schema.HealthWeightUpdate
    ),
    user_id: int,
    db: Session,
) -> health_weight_schema.HealthWeightCreate | health_weight_schema.HealthWeightUpdate:
    """
    Calculate the Body Mass Index (BMI) for a health weight record.

    Args:
        health_weight: Health weight record with weight value.
        user_id: Unique identifier of the user.
        db: Database session.

    Returns:
        Updated health weight record with calculated BMI.
    """
    # Get the user from the database
    user = users_crud.get_user_by_id(user_id, db)

    # Calculate BMI if user and required data exist
    calculated_bmi = None
    if (
        user is not None
        and user.height is not None
        and health_weight.weight is not None
    ):
        # Calculate the bmi: weight (kg) / (height (m))^2
        calculated_bmi = float(health_weight.weight) / ((user.height / 100) ** 2)

    # Return updated model with BMI
    return health_weight.model_copy(update={"bmi": calculated_bmi})

calculate_bmi_all_user_entries

calculate_bmi_all_user_entries(user_id, db)

Calculate and update BMI for all health weight entries.

Parameters:

Name Type Description Default
user_id int

User ID whose entries should be processed.

required
db Session

Database session.

required

Returns:

Type Description
None

None

Source code in backend/app/health/health_weight/utils.py
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
def calculate_bmi_all_user_entries(user_id: int, db: Session) -> None:
    """
    Calculate and update BMI for all health weight entries.

    Args:
        user_id: User ID whose entries should be processed.
        db: Database session.

    Returns:
        None
    """
    # Get all the health data entries for the user
    health_weight_entries = health_weight_crud.get_all_health_weight_by_user_id(
        user_id, db
    )

    # Check if health data entries exist
    if health_weight_entries:
        # Loop through and calculate BMI for each entry
        for health_weight in health_weight_entries:
            # Convert to update schema with the existing ID
            aux_health_weight = health_weight_schema.HealthWeightUpdate.model_validate(
                health_weight
            )
            updated_weight = cast(
                health_weight_schema.HealthWeightUpdate,
                calculate_bmi(aux_health_weight, user_id, db),
            )
            health_weight_crud.edit_health_weight(user_id, updated_weight, db)

create_health_weight

create_health_weight(user_id, health_weight, db)

Create a new health weight entry for a user.

This function creates a new health weight record in the database. If the date is not provided, it defaults to the current date. If BMI is not provided, it is automatically calculated using the user's height and the provided weight.

Parameters:

Name Type Description Default
user_id int

The ID of the user for whom the health weight entry is being created.

required
health_weight HealthWeightCreate

The health weight data to be created, containing fields such as weight, date, and optionally BMI.

required
db Session

The database session used for database operations.

required

Returns:

Type Description
HealthWeight

health_weight_models.HealthWeightCreate: The created health weight model instance.

Raises:

Type Description
HTTPException
  • 409 Conflict: If a duplicate entry exists for the same date.
  • 500 Internal Server Error: If any other unexpected error occurs during creation.
Note
  • The function automatically sets the date to current timestamp if not provided.
  • BMI is calculated automatically if not provided in the input.
  • The database transaction is rolled back in case of any errors.
Source code in backend/app/health/health_weight/crud.py
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
@core_decorators.handle_db_errors
def create_health_weight(
    user_id: int, health_weight: health_weight_schema.HealthWeightCreate, db: Session
) -> health_weight_models.HealthWeight:
    """
    Create a new health weight entry for a user.

    This function creates a new health weight record in the database. If the date is not provided,
    it defaults to the current date. If BMI is not provided, it is automatically calculated
    using the user's height and the provided weight.

    Args:
        user_id (int): The ID of the user for whom the health weight entry is being created.
        health_weight (health_weight_schema.HealthWeightCreate): The health weight data to be created,
            containing fields such as weight, date, and optionally BMI.
        db (Session): The database session used for database operations.

    Returns:
        health_weight_models.HealthWeightCreate: The created health weight model instance.

    Raises:
        HTTPException:
            - 409 Conflict: If a duplicate entry exists for the same date.
            - 500 Internal Server Error: If any other unexpected error occurs during creation.

    Note:
        - The function automatically sets the date to current timestamp if not provided.
        - BMI is calculated automatically if not provided in the input.
        - The database transaction is rolled back in case of any errors.
    """
    try:
        # Check if bmi is None
        if health_weight.bmi is None:
            health_weight = cast(
                health_weight_schema.HealthWeightCreate,
                health_weight_utils.calculate_bmi(health_weight, user_id, db),
            )

        # Create a new health_weight
        db_health_weight = health_weight_models.HealthWeight(
            **health_weight.model_dump(exclude_none=False),
            user_id=user_id,
        )

        # Add the health_weight to the database
        db.add(db_health_weight)
        db.commit()
        db.refresh(db_health_weight)

        # Return the health_weight
        return db_health_weight
    except IntegrityError as integrity_error:
        # Rollback the transaction
        db.rollback()

        # Raise an HTTPException with a 409 Internal Server Error status code
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Duplicate entry error. Check if there is already a entry created for {health_weight.date}",
        ) from integrity_error

delete_health_weight

delete_health_weight(user_id, health_weight_id, db)

Delete a health weight record for a user.

Parameters:

Name Type Description Default
user_id int

User ID who owns the health weight record.

required
health_weight_id int

Health weight record ID to delete.

required
db Session

Database session.

required

Returns:

Type Description
None

None

Raises:

Type Description
HTTPException

If record not found or database error.

Source code in backend/app/health/health_weight/crud.py
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
319
320
321
322
323
324
325
326
327
@core_decorators.handle_db_errors
def delete_health_weight(user_id: int, health_weight_id: int, db: Session) -> None:
    """
    Delete a health weight record for a user.

    Args:
        user_id: User ID who owns the health weight record.
        health_weight_id: Health weight record ID to delete.
        db: Database session.

    Returns:
        None

    Raises:
        HTTPException: If record not found or database error.
    """
    # Get and delete the health_weight
    db_health_weight = get_health_weight_by_id_and_user_id(
        health_weight_id, user_id, db
    )

    # Check if the health_weight was found
    if db_health_weight is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=(
                f"Health weight with id {health_weight_id} "
                f"for user {user_id} not found"
            ),
        )

    # Delete the record
    db.delete(db_health_weight)
    db.commit()

edit_health_weight

edit_health_weight(user_id, health_weight, db)

Edit an existing health weight record for a user.

Parameters:

Name Type Description Default
user_id int

User ID who owns the health weight record.

required
health_weight HealthWeightUpdate

Health weight data to update.

required
db Session

Database session.

required

Returns:

Type Description
HealthWeight

Updated health weight object.

Raises:

Type Description
HTTPException

If record not found or database error.

Source code in backend/app/health/health_weight/crud.py
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
@core_decorators.handle_db_errors
def edit_health_weight(
    user_id: int,
    health_weight: health_weight_schema.HealthWeightUpdate,
    db: Session,
) -> health_weight_models.HealthWeight:
    """
    Edit an existing health weight record for a user.

    Args:
        user_id: User ID who owns the health weight record.
        health_weight: Health weight data to update.
        db: Database session.

    Returns:
        Updated health weight object.

    Raises:
        HTTPException: If record not found or database error.
    """
    # Ensure the health_weight belongs to the user
    if health_weight.user_id != user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Cannot edit health weight for another user.",
        )

    # Get the health_weight from the database
    db_health_weight = get_health_weight_by_id_and_user_id(
        health_weight.id, user_id, db
    )

    if db_health_weight is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Health weight not found",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Check if bmi is None
    if health_weight.bmi is None and health_weight.weight is not None:
        health_weight = cast(
            health_weight_schema.HealthWeightUpdate,
            health_weight_utils.calculate_bmi(health_weight, user_id, db),
        )

    # Dictionary of fields to update if they are not None
    health_weight_data = health_weight.model_dump(exclude_unset=True)
    # Iterate over the fields and update dynamically
    for key, value in health_weight_data.items():
        setattr(db_health_weight, key, value)

    # Commit the transaction and refresh
    db.commit()
    db.refresh(db_health_weight)

    return db_health_weight

get_all_health_weight

get_all_health_weight(db)

Retrieve all health weight records from the database.

Parameters:

Name Type Description Default
db Session

Database session.

required

Returns:

Type Description
list[HealthWeight]

List of HealthWeight models ordered by date descending.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_weight/crud.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@core_decorators.handle_db_errors
def get_all_health_weight(
    db: Session,
) -> list[health_weight_models.HealthWeight]:
    """
    Retrieve all health weight records from the database.

    Args:
        db: Database session.

    Returns:
        List of HealthWeight models ordered by date descending.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the health_weight from the database
    stmt = select(health_weight_models.HealthWeight).order_by(
        desc(health_weight_models.HealthWeight.date)
    )
    return db.execute(stmt).scalars().all()

get_all_health_weight_by_user_id

get_all_health_weight_by_user_id(user_id, db)

Retrieve all health weight records for a user.

Parameters:

Name Type Description Default
user_id int

User ID to fetch records for.

required
db Session

Database session.

required

Returns:

Type Description
list[HealthWeight]

List of HealthWeight models ordered by date descending.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_weight/crud.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@core_decorators.handle_db_errors
def get_all_health_weight_by_user_id(
    user_id: int, db: Session
) -> list[health_weight_models.HealthWeight]:
    """
    Retrieve all health weight records for a user.

    Args:
        user_id: User ID to fetch records for.
        db: Database session.

    Returns:
        List of HealthWeight models ordered by date descending.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the health_weight from the database
    stmt = (
        select(health_weight_models.HealthWeight)
        .where(health_weight_models.HealthWeight.user_id == user_id)
        .order_by(desc(health_weight_models.HealthWeight.date))
    )
    return db.execute(stmt).scalars().all()

get_health_weight_by_date

get_health_weight_by_date(user_id, date, db)

Retrieve health weight record for a user on a specific date.

Parameters:

Name Type Description Default
user_id int

User ID.

required
date str

Date string for the weight record.

required
db Session

Database session.

required

Returns:

Type Description
HealthWeight | None

HealthWeight model if found, None otherwise.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_weight/crud.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
@core_decorators.handle_db_errors
def get_health_weight_by_date(
    user_id: int, date: str, db: Session
) -> health_weight_models.HealthWeight | None:
    """
    Retrieve health weight record for a user on a specific date.

    Args:
        user_id: User ID.
        date: Date string for the weight record.
        db: Database session.

    Returns:
        HealthWeight model if found, None otherwise.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the health_weight from the database
    stmt = select(health_weight_models.HealthWeight).where(
        health_weight_models.HealthWeight.date == func.date(date),
        health_weight_models.HealthWeight.user_id == user_id,
    )
    return db.execute(stmt).scalar_one_or_none()

get_health_weight_by_id_and_user_id

get_health_weight_by_id_and_user_id(health_weight_id, user_id, db)

Retrieve health weight record by ID and user ID.

Parameters:

Name Type Description Default
health_weight_id int

Health weight record ID to fetch.

required
user_id int

User ID to fetch record for.

required
db Session

Database session.

required

Returns:

Type Description
HealthWeight | None

HealthWeight model if found, None otherwise.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_weight/crud.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
@core_decorators.handle_db_errors
def get_health_weight_by_id_and_user_id(
    health_weight_id: int, user_id: int, db: Session
) -> health_weight_models.HealthWeight | None:
    """
    Retrieve health weight record by ID and user ID.

    Args:
        health_weight_id: Health weight record ID to fetch.
        user_id: User ID to fetch record for.
        db: Database session.

    Returns:
        HealthWeight model if found, None otherwise.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the health_weight from the database
    stmt = select(health_weight_models.HealthWeight).where(
        health_weight_models.HealthWeight.id == health_weight_id,
        health_weight_models.HealthWeight.user_id == user_id,
    )
    return db.execute(stmt).scalar_one_or_none()

get_health_weight_number

get_health_weight_number(user_id, db)

Retrieve total count of health weight records for a user.

Parameters:

Name Type Description Default
user_id int

User ID to count records for.

required
db Session

Database session.

required

Returns:

Type Description
int

Total number of health weight records.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_weight/crud.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@core_decorators.handle_db_errors
def get_health_weight_number(user_id: int, db: Session) -> int:
    """
    Retrieve total count of health weight records for a user.

    Args:
        user_id: User ID to count records for.
        db: Database session.

    Returns:
        Total number of health weight records.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the number of health_weight from the database
    stmt = (
        select(func.count())
        .select_from(health_weight_models.HealthWeight)
        .where(health_weight_models.HealthWeight.user_id == user_id)
    )
    return db.execute(stmt).scalar_one()

get_health_weight_with_pagination

get_health_weight_with_pagination(user_id, db, page_number=1, num_records=5)

Retrieve paginated health weight records for a user.

Parameters:

Name Type Description Default
user_id int

User ID to fetch records for.

required
db Session

Database session.

required
page_number int

Page number to retrieve (1-indexed).

1
num_records int

Number of records per page.

5

Returns:

Type Description
list[HealthWeight]

List of HealthWeight models for the requested page.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_weight/crud.py
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
@core_decorators.handle_db_errors
def get_health_weight_with_pagination(
    user_id: int,
    db: Session,
    page_number: int = 1,
    num_records: int = 5,
) -> list[health_weight_models.HealthWeight]:
    """
    Retrieve paginated health weight records for a user.

    Args:
        user_id: User ID to fetch records for.
        db: Database session.
        page_number: Page number to retrieve (1-indexed).
        num_records: Number of records per page.

    Returns:
        List of HealthWeight models for the requested page.

    Raises:
        HTTPException: If database error occurs.
    """
    # Get the health_weight from the database
    stmt = (
        select(health_weight_models.HealthWeight)
        .where(health_weight_models.HealthWeight.user_id == user_id)
        .order_by(desc(health_weight_models.HealthWeight.date))
        .offset((page_number - 1) * num_records)
        .limit(num_records)
    )
    return db.execute(stmt).scalars().all()