Skip to content

API Reference

Health poop module for managing user bowel movement data.

This module provides CRUD operations and data models for user bowel movement tracking including daily records, Bristol stool scale type, and optional notes.

Exports
  • CRUD: get_health_poop_number_by_user_id, get_health_poop_by_id_and_user_id, get_health_poop_by_user_id, get_health_poop_by_date_and_user_id, create_health_poop, edit_health_poop, delete_health_poop
  • Schemas: HealthPoopBase, HealthPoopCreate, HealthPoopUpdate, HealthPoopRead, HealthPoopListResponse
  • Enums: Source, BristolType
  • Models: HealthPoop (ORM model)

BristolType

Bases: Enum

Bristol Stool Scale classification types.

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/health/health_poop/schema.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class BristolType(Enum):
    """
    Bristol Stool Scale classification types.

    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 = 1
    TYPE_2 = 2
    TYPE_3 = 3
    TYPE_4 = 4
    TYPE_5 = 5
    TYPE_6 = 6
    TYPE_7 = 7

HealthPoopBase

Bases: BaseModel

Base model for health poop data.

Attributes:

Name Type Description
date_time datetime | None

Date and time of the bowel movement.

bristol_type BristolType | None

Bristol Stool Scale type (1-7).

color Color | None

Stool color description.

notes StrictStr | None

Optional notes about the bowel movement.

source Source | None

Source of the data.

Source code in backend/app/health/health_poop/schema.py
 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
121
122
123
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 (1-7).
        color: Stool color description.
        notes: Optional notes about the bowel movement.
        source: Source of the data.
    """

    date_time: datetime | None = Field(
        default=None,
        description="Date and time of the bowel movement",
    )
    bristol_type: BristolType | None = Field(
        default=None,
        description="Bristol Stool Scale type (1-7)",
    )
    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"
        ),
    )
    source: Source | None = Field(
        default=None,
        description="Source of the data",
    )

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

HealthPoopCreate

Bases: HealthPoopBase

Schema for creating a new poop record.

Requires date_time and sets defaults for source.

Source code in backend/app/health/health_poop/schema.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class HealthPoopCreate(HealthPoopBase):
    """
    Schema for creating a new poop record.

    Requires date_time and sets defaults for source.
    """

    @model_validator(mode="after")
    def set_defaults_and_validate(
        self,
    ) -> "HealthPoopCreate":
        """
        Validate required fields and set defaults.

        Returns:
            The validated model instance with defaults set.

        Raises:
            ValueError: If date_time is not provided.
        """
        if self.date_time is None:
            raise ValueError("date_time is required")
        if self.source is None:
            self.source = Source.MANUAL
        return self

set_defaults_and_validate

set_defaults_and_validate()

Validate required fields and set defaults.

Returns:

Type Description
HealthPoopCreate

The validated model instance with defaults set.

Raises:

Type Description
ValueError

If date_time is not provided.

Source code in backend/app/health/health_poop/schema.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@model_validator(mode="after")
def set_defaults_and_validate(
    self,
) -> "HealthPoopCreate":
    """
    Validate required fields and set defaults.

    Returns:
        The validated model instance with defaults set.

    Raises:
        ValueError: If date_time is not provided.
    """
    if self.date_time is None:
        raise ValueError("date_time is required")
    if self.source is None:
        self.source = Source.MANUAL
    return self

HealthPoopListResponse

Bases: HealthListResponse

Response model for listing health poop records.

Attributes:

Name Type Description
records list[HealthPoopRead]

A list of HealthPoopRead objects representing individual bowel movement records.

Source code in backend/app/health/health_poop/schema.py
183
184
185
186
187
188
189
190
191
192
193
194
195
class HealthPoopListResponse(health_schema.HealthListResponse):
    """
    Response model for listing health poop records.

    Attributes:
        records: A list of HealthPoopRead objects representing
            individual bowel movement records.
    """

    records: list[HealthPoopRead] = Field(
        ...,
        description="List of health poop records",
    )

HealthPoopModel

Bases: Base

User bowel movement tracking data.

Attributes:

Name Type Description
id Mapped[int]

Primary key, auto-incremented unique identifier.

user_id Mapped[int]

Foreign key referencing users.id.

date_time Mapped[datetime]

Date and time of the bowel movement.

bristol_type Mapped[int | None]

Bristol Stool Scale type (1-7).

color Mapped[str | None]

Stool color description.

notes Mapped[str | None]

Optional notes about the bowel movement.

source Mapped[str | None]

Source of the data.

user Mapped[str | None]

Relationship to the Users model.

Table

health_poop

Relationships
  • Many-to-One with Users model through user_id
Source code in backend/app/health/health_poop/models.py
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
class HealthPoop(Base):
    """
    User bowel movement tracking data.

    Attributes:
        id: Primary key, auto-incremented unique identifier.
        user_id: Foreign key referencing users.id.
        date_time: Date and time of the bowel movement.
        bristol_type: Bristol Stool Scale type (1-7).
        color: Stool color description.
        notes: Optional notes about the bowel movement.
        source: Source of the data.
        user: Relationship to the Users model.

    Table:
        health_poop

    Relationships:
        - Many-to-One with Users model through user_id
    """

    __tablename__ = "health_poop"

    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_poop belongs",
    )
    date_time: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        nullable=False,
        index=True,
        comment="Date and time of bowel movement",
    )
    bristol_type: Mapped[int | None] = mapped_column(
        nullable=True,
        comment="Bristol Stool Scale type (1-7)",
    )
    color: Mapped[str | None] = mapped_column(
        String(50),
        nullable=True,
        comment="Stool color description",
    )
    notes: Mapped[str | None] = mapped_column(
        String(500),
        nullable=True,
        comment="Optional notes about the bowel movement",
    )
    source: Mapped[str | None] = mapped_column(
        String(250),
        nullable=True,
        comment="Source of the health poop data",
    )

    # Define a relationship to the Users model
    users: Mapped["Users"] = relationship(back_populates="health_poop")

HealthPoopRead

Bases: HealthPoopBase

Schema for reading a poop record.

Attributes:

Name Type Description
id StrictInt

Unique identifier for the poop record.

user_id StrictInt

Foreign key reference to the user.

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

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

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

HealthPoopUpdate

Bases: HealthPoopRead

Schema for updating a poop record.

Inherits from HealthPoopRead for consistency with read operations while allowing modifications to poop data.

Source code in backend/app/health/health_poop/schema.py
174
175
176
177
178
179
180
class HealthPoopUpdate(HealthPoopRead):
    """
    Schema for updating a poop record.

    Inherits from HealthPoopRead for consistency with read
    operations while allowing modifications to poop data.
    """

Source

Bases: Enum

Enumeration of data sources for poop records.

Attributes:

Name Type Description
MANUAL

Manually entered data.

Source code in backend/app/health/health_poop/schema.py
23
24
25
26
27
28
29
30
31
class Source(Enum):
    """
    Enumeration of data sources for poop records.

    Attributes:
        MANUAL: Manually entered data.
    """

    MANUAL = "manual"

create_health_poop

create_health_poop(user_id, health_poop, db)

Create a new poop record for a user.

Parameters:

Name Type Description Default
user_id int

User ID for the record owner.

required
health_poop HealthPoopCreate

Poop data to create.

required
db Session

Database session.

required

Returns:

Type Description
HealthPoop

Created poop record.

Raises:

Type Description
HTTPException

If database integrity error.

Source code in backend/app/health/health_poop/crud.py
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
@core_decorators.handle_db_errors
def create_health_poop(
    user_id: int,
    health_poop: health_poop_schema.HealthPoopCreate,
    db: Session,
) -> health_poop_models.HealthPoop:
    """
    Create a new poop record for a user.

    Args:
        user_id: User ID for the record owner.
        health_poop: Poop data to create.
        db: Database session.

    Returns:
        Created poop record.

    Raises:
        HTTPException: If database integrity error.
    """
    try:
        db_health_poop = health_poop_models.HealthPoop(
            **health_poop.model_dump(exclude_none=False),
            user_id=user_id,
        )

        db.add(db_health_poop)
        db.commit()
        db.refresh(db_health_poop)

        return db_health_poop
    except IntegrityError as integrity_error:
        db.rollback()

        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=(
                "Failed to create poop record."
                " Database integrity error."
            ),
        ) from integrity_error

delete_health_poop

delete_health_poop(user_id, health_poop_id, db)

Delete a poop record for a user.

Parameters:

Name Type Description Default
user_id int

User ID who owns the record.

required
health_poop_id int

Poop 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_poop/crud.py
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
@core_decorators.handle_db_errors
def delete_health_poop(
    user_id: int, health_poop_id: int, db: Session
) -> None:
    """
    Delete a poop record for a user.

    Args:
        user_id: User ID who owns the record.
        health_poop_id: Poop record ID to delete.
        db: Database session.

    Returns:
        None

    Raises:
        HTTPException: If record not found or database error.
    """
    db_health_poop = get_health_poop_by_id_and_user_id(
        health_poop_id, user_id, db
    )

    if db_health_poop is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Health poop record not found",
        ) from None

    db.delete(db_health_poop)
    db.commit()

edit_health_poop

edit_health_poop(user_id, health_poop, db)

Edit poop record for a user.

Parameters:

Name Type Description Default
user_id int

User ID who owns the record.

required
health_poop HealthPoopUpdate

Poop data to update.

required
db Session

Database session.

required

Returns:

Type Description
HealthPoop

Updated HealthPoop model.

Raises:

Type Description
HTTPException

403 if editing another user's record, 404 if not found, 500 if database error.

Source code in backend/app/health/health_poop/crud.py
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
@core_decorators.handle_db_errors
def edit_health_poop(
    user_id: int,
    health_poop: health_poop_schema.HealthPoopUpdate,
    db: Session,
) -> health_poop_models.HealthPoop:
    """
    Edit poop record for a user.

    Args:
        user_id: User ID who owns the record.
        health_poop: Poop data to update.
        db: Database session.

    Returns:
        Updated HealthPoop model.

    Raises:
        HTTPException: 403 if editing another user's record,
            404 if not found, 500 if database error.
    """
    if health_poop.user_id != user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=(
                "Cannot edit health poop record"
                " for another user."
            ),
        )

    db_health_poop = get_health_poop_by_id_and_user_id(
        health_poop.id, user_id, db
    )

    if db_health_poop is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Health poop record not found",
        ) from None

    health_poop_data = health_poop.model_dump(
        exclude_unset=True
    )
    for key, value in health_poop_data.items():
        setattr(db_health_poop, key, value)

    db.commit()
    db.refresh(db_health_poop)

    return db_health_poop

get_health_poop_by_date_and_user_id

get_health_poop_by_date_and_user_id(user_id, date, db)

Retrieve poop records for a user on a specific date.

Unlike other health modules, poop can have multiple entries per day, so this returns a list.

Parameters:

Name Type Description Default
user_id int

User ID.

required
date str

Date string for the poop records.

required
db Session

Database session.

required

Returns:

Type Description
list[HealthPoop]

List of HealthPoop models for the given date.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_poop/crud.py
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
167
168
169
170
171
@core_decorators.handle_db_errors
def get_health_poop_by_date_and_user_id(
    user_id: int, date: str, db: Session
) -> list[health_poop_models.HealthPoop]:
    """
    Retrieve poop records for a user on a specific date.

    Unlike other health modules, poop can have multiple entries
    per day, so this returns a list.

    Args:
        user_id: User ID.
        date: Date string for the poop records.
        db: Database session.

    Returns:
        List of HealthPoop models for the given date.

    Raises:
        HTTPException: If database error occurs.
    """
    stmt = (
        select(health_poop_models.HealthPoop)
        .where(
            func.date(
                health_poop_models.HealthPoop.date_time
            )
            == func.date(date),
            health_poop_models.HealthPoop.user_id
            == user_id,
        )
        .order_by(
            desc(health_poop_models.HealthPoop.date_time)
        )
    )
    return db.execute(stmt).scalars().all()

get_health_poop_by_id_and_user_id

get_health_poop_by_id_and_user_id(health_poop_id, user_id, db)

Retrieve poop record by ID and user ID.

Parameters:

Name Type Description Default
health_poop_id int

Poop record ID to fetch.

required
user_id int

User ID to fetch record for.

required
db Session

Database session.

required

Returns:

Type Description
HealthPoop | None

HealthPoop model if found, None otherwise.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_poop/crud.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@core_decorators.handle_db_errors
def get_health_poop_by_id_and_user_id(
    health_poop_id: int, user_id: int, db: Session
) -> health_poop_models.HealthPoop | None:
    """
    Retrieve poop record by ID and user ID.

    Args:
        health_poop_id: Poop record ID to fetch.
        user_id: User ID to fetch record for.
        db: Database session.

    Returns:
        HealthPoop model if found, None otherwise.

    Raises:
        HTTPException: If database error occurs.
    """
    stmt = select(health_poop_models.HealthPoop).where(
        health_poop_models.HealthPoop.id == health_poop_id,
        health_poop_models.HealthPoop.user_id == user_id,
    )
    return db.execute(stmt).scalar_one_or_none()

get_health_poop_by_user_id

get_health_poop_by_user_id(user_id, db, page_number=None, num_records=None, interval=None)

Retrieve poop records for a user with optional pagination and filtering.

Parameters:

Name Type Description Default
user_id int

User ID whose records are to be retrieved.

required
db Session

Database session used to execute the query.

required
page_number int | None

Page number for pagination (1-indexed).

None
num_records int | None

Number of records per page.

None
interval Interval | None

Time interval to filter records.

None

Returns:

Type Description
list[HealthPoop]

List of HealthPoop records sorted by date_time descending.

Source code in backend/app/health/health_poop/crud.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
@core_decorators.handle_db_errors
def get_health_poop_by_user_id(
    user_id: int,
    db: Session,
    page_number: int | None = None,
    num_records: int | None = None,
    interval: health_constants.Interval | None = None,
) -> list[health_poop_models.HealthPoop]:
    """
    Retrieve poop records for a user with optional pagination
    and filtering.

    Args:
        user_id: User ID whose records are to be retrieved.
        db: Database session used to execute the query.
        page_number: Page number for pagination (1-indexed).
        num_records: Number of records per page.
        interval: Time interval to filter records.

    Returns:
        List of HealthPoop records sorted by date_time
            descending.
    """
    stmt = select(health_poop_models.HealthPoop).where(
        health_poop_models.HealthPoop.user_id == user_id
    )

    if interval is not None:
        stmt = stmt.where(
            health_poop_models.HealthPoop.date_time
            >= health_utils.get_start_date_for_interval(
                interval.value
            )
        )

    stmt = stmt.order_by(
        desc(health_poop_models.HealthPoop.date_time)
    )

    if page_number is not None and num_records is not None:
        stmt = stmt.offset(
            (page_number - 1) * num_records
        ).limit(num_records)

    return db.execute(stmt).scalars().all()

get_health_poop_number_by_user_id

get_health_poop_number_by_user_id(user_id, db, interval=None)

Retrieve total count of poop records for a user.

If interval is provided, count only records starting from the calculated start date.

Parameters:

Name Type Description Default
user_id int

User ID to count records for.

required
db Session

Database session.

required
interval Interval | None

Optional filter by goal interval.

None

Returns:

Type Description
int

Total number of health poop records.

Raises:

Type Description
HTTPException

If database error occurs.

Source code in backend/app/health/health_poop/crud.py
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
@core_decorators.handle_db_errors
def get_health_poop_number_by_user_id(
    user_id: int,
    db: Session,
    interval: health_constants.Interval | None = None,
) -> int:
    """
    Retrieve total count of poop records for a user.

    If interval is provided, count only records starting from
    the calculated start date.

    Args:
        user_id: User ID to count records for.
        db: Database session.
        interval: Optional filter by goal interval.

    Returns:
        Total number of health poop records.

    Raises:
        HTTPException: If database error occurs.
    """
    stmt = (
        select(func.count())
        .select_from(health_poop_models.HealthPoop)
        .where(
            health_poop_models.HealthPoop.user_id == user_id
        )
    )

    if interval is not None:
        stmt = stmt.where(
            health_poop_models.HealthPoop.date_time
            >= health_utils.get_start_date_for_interval(
                interval.value
            )
        )

    return db.execute(stmt).scalar_one()