Skip to content

API Reference

Health targets module for managing user health goals.

This module provides CRUD operations and data models for user health targets including weight, steps, and sleep goals.

Exports
  • CRUD: get_health_targets_by_user_id, create_health_targets, edit_health_target
  • Schemas: HealthTargetsBase, HealthTargetsUpdate, HealthTargetsRead
  • Models: HealthTargets (ORM model)

HealthTargetsBase

Bases: BaseModel

Base schema for health targets with shared fields.

Attributes:

Name Type Description
weight StrictFloat | None

Target weight in kg.

steps StrictInt | None

Target daily steps count.

sleep StrictInt | None

Target sleep duration in seconds.

Source code in backend/app/health/health_targets/schema.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class HealthTargetsBase(BaseModel):
    """
    Base schema for health targets with shared fields.

    Attributes:
        weight: Target weight in kg.
        steps: Target daily steps count.
        sleep: Target sleep duration in seconds.
    """

    weight: StrictFloat | None = Field(
        default=None, gt=0, le=500, description="Target weight in kg"
    )
    steps: StrictInt | None = Field(
        default=None, ge=0, description="Target daily steps count"
    )
    sleep: StrictInt | None = Field(
        default=None, ge=0, le=86400, description="Target sleep duration in seconds"
    )

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

HealthTargetsModel

Bases: Base

User health targets configuration.

Attributes:

Name Type Description
id Mapped[int]

Primary key.

user_id Mapped[int]

Foreign key to users table (unique).

weight Mapped[Decimal | None]

Target weight in kg.

steps Mapped[int | None]

Target daily steps count.

sleep Mapped[int | None]

Target sleep duration in seconds.

user Mapped[int | None]

Relationship to Users model.

Source code in backend/app/health/health_targets/models.py
 7
 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
class HealthTargets(Base):
    """
    User health targets configuration.

    Attributes:
        id: Primary key.
        user_id: Foreign key to users table (unique).
        weight: Target weight in kg.
        steps: Target daily steps count.
        sleep: Target sleep duration in seconds.
        user: Relationship to Users model.
    """

    __tablename__ = "health_targets"

    id: Mapped[int] = mapped_column(
        primary_key=True,
        autoincrement=True,
    )
    user_id: Mapped[int] = mapped_column(
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
        unique=True,
        index=True,
        comment="User ID that the health_target belongs",
    )
    weight: Mapped[Decimal | None] = mapped_column(
        Numeric(precision=10, scale=2),
        nullable=True,
        comment="Weight in kg",
    )
    steps: Mapped[int | None] = mapped_column(
        nullable=True,
        comment="Number of steps taken",
    )
    sleep: Mapped[int | None] = mapped_column(
        nullable=True,
        comment="Number of hours slept in seconds",
    )

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

HealthTargetsRead

Bases: HealthTargetsBase

Schema for reading health targets.

Attributes:

Name Type Description
id StrictInt

Unique identifier for the health target record.

user_id StrictInt

Foreign key reference to the user.

Source code in backend/app/health/health_targets/schema.py
31
32
33
34
35
36
37
38
39
40
41
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.
    """

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

HealthTargetsUpdate

Bases: HealthTargetsRead

Schema for updating health targets.

Inherits all validation from HealthTargetsRead. All fields are optional for partial updates.

Source code in backend/app/health/health_targets/schema.py
44
45
46
47
48
49
50
class HealthTargetsUpdate(HealthTargetsRead):
    """
    Schema for updating health targets.

    Inherits all validation from HealthTargetsRead.
    All fields are optional for partial updates.
    """

create_health_targets

create_health_targets(user_id, db)

Create new health targets for a user.

Parameters:

Name Type Description Default
user_id int

The ID of the user to create targets for.

required
db Session

SQLAlchemy database session.

required

Returns:

Type Description
HealthTargets

The created HealthTargetsRead schema.

Raises:

Type Description
HTTPException

409 error if targets already exist.

HTTPException

500 error if database operation fails.

Source code in backend/app/health/health_targets/crud.py
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
@core_decorators.handle_db_errors
def create_health_targets(
    user_id: int, db: Session
) -> health_targets_models.HealthTargets:
    """
    Create new health targets for a user.

    Args:
        user_id: The ID of the user to create targets for.
        db: SQLAlchemy database session.

    Returns:
        The created HealthTargetsRead schema.

    Raises:
        HTTPException: 409 error if targets already exist.
        HTTPException: 500 error if database operation fails.
    """
    try:
        # Create a new health_target
        db_health_targets = health_targets_models.HealthTargets(
            user_id=user_id,
        )

        # Add the health_targets to the database
        db.add(db_health_targets)
        db.commit()
        db.refresh(db_health_targets)

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

        # Raise an HTTPException with a 409 Conflict status code
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Duplicate entry error. Check if there is "
            "already an entry created for the user",
        ) from integrity_error

edit_health_target

edit_health_target(health_target, user_id, db)

Update health targets for a specific user.

Parameters:

Name Type Description Default
health_target HealthTargetsUpdate

Schema with fields to update.

required
user_id int

The ID of the user to update targets for.

required
db Session

SQLAlchemy database session.

required

Returns:

Type Description
HealthTargets

The updated HealthTargets model.

Raises:

Type Description
HTTPException

404 error if targets not found.

HTTPException

500 error if database operation fails.

Source code in backend/app/health/health_targets/crud.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
111
112
113
114
115
116
117
118
119
120
@core_decorators.handle_db_errors
def edit_health_target(
    health_target: health_targets_schema.HealthTargetsUpdate,
    user_id: int,
    db: Session,
) -> health_targets_models.HealthTargets:
    """
    Update health targets for a specific user.

    Args:
        health_target: Schema with fields to update.
        user_id: The ID of the user to update targets for.
        db: SQLAlchemy database session.

    Returns:
        The updated HealthTargets model.

    Raises:
        HTTPException: 404 error if targets not found.
        HTTPException: 500 error if database operation fails.
    """
    # Get the user health target from the database
    db_health_target = get_health_targets_by_user_id(user_id, db)

    if db_health_target is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User health target not found",
            headers={"WWW-Authenticate": "Bearer"},
        )

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

    # Commit the transaction
    db.commit()
    db.refresh(db_health_target)

    return db_health_target

get_health_targets_by_user_id

get_health_targets_by_user_id(user_id, db)

Retrieve health targets for a specific user.

Parameters:

Name Type Description Default
user_id int

The ID of the user to fetch targets for.

required
db Session

SQLAlchemy database session.

required

Returns:

Type Description
HealthTargets | None

The HealthTargets model if found, None otherwise.

Raises:

Type Description
HTTPException

500 error if database query fails.

Source code in backend/app/health/health_targets/crud.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@core_decorators.handle_db_errors
def get_health_targets_by_user_id(
    user_id: int, db: Session
) -> health_targets_models.HealthTargets | None:
    """
    Retrieve health targets for a specific user.

    Args:
        user_id: The ID of the user to fetch targets for.
        db: SQLAlchemy database session.

    Returns:
        The HealthTargets model if found, None otherwise.

    Raises:
        HTTPException: 500 error if database query fails.
    """
    # Get the health_targets from the database
    stmt = select(health_targets_models.HealthTargets).where(
        health_targets_models.HealthTargets.user_id == user_id
    )
    return db.execute(stmt).scalar_one_or_none()