Skip to content

API Reference

Client

Synchronous client for the Habitify API v2.

The client can be used as a context manager so the underlying HTTP session is closed automatically::

with HabitipyClient(api_key="...") as client:
    page = client.habits.list()

You may also bring your own :class:httpx.Client and manage its lifecycle yourself::

http = httpx.Client()
client = HabitipyClient(api_key="...", client=http)
# ... use client ...
http.close()

Attributes:

Name Type Description
habits

Namespace for habit-related endpoints.

areas

Namespace for area-related endpoints.

Source code in habitipie/client.py
 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
 98
 99
100
101
102
103
104
105
106
107
108
109
class HabitipyClient:
    """Synchronous client for the Habitify API v2.

    The client can be used as a context manager so the underlying HTTP session
    is closed automatically::

        with HabitipyClient(api_key="...") as client:
            page = client.habits.list()

    You may also bring your own :class:`httpx.Client` and manage its lifecycle
    yourself::

        http = httpx.Client()
        client = HabitipyClient(api_key="...", client=http)
        # ... use client ...
        http.close()

    Attributes:
        habits: Namespace for habit-related endpoints.
        areas: Namespace for area-related endpoints.
    """

    def __init__(
        self,
        api_key: str | None = None,
        *,
        client: httpx.Client | None = None,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = DEFAULT_TIMEOUT,
    ) -> None:
        """Create a new Habitipy client.

        Args:
            api_key: Habitify API key. Required when *client* is not provided
                and must be a non-empty string.
            client: An existing :class:`httpx.Client` to use for requests. When
                provided, the caller is responsible for closing it.
            base_url: Base URL for the Habitify API. Defaults to the production
                v2 endpoint.
            timeout: Default timeout in seconds for HTTP requests. Ignored when
                *client* is injected.

        Raises:
            ValueError: If *api_key* is missing, empty, or the injected *client*
                lacks the ``X-API-Key`` header.
        """
        if client is None:
            if api_key is None or api_key == "":
                raise ValueError("api_key is required when client is not provided.")

        self._owns_client = client is None
        default_headers: dict[str, str] | None = None
        if client is None:
            default_headers = {API_KEY_HEADER: cast(str, api_key)}

        self._client = client or httpx.Client(
            base_url=base_url.rstrip("/"),
            timeout=timeout,
            headers=default_headers,
        )

        if client is not None:
            if not str(self._client.base_url):
                self._client.base_url = httpx.URL(base_url.rstrip("/"))

            if api_key is not None and api_key != "":
                self._client.headers[API_KEY_HEADER] = api_key

            if API_KEY_HEADER not in self._client.headers:
                raise ValueError(
                    "api_key is required unless the provided client already has "
                    f"an {API_KEY_HEADER} header."
                )

        self.habits = HabitsResource(self._client)
        self.areas = AreasResource(self._client)

    def close(self) -> None:
        if self._owns_client:
            self._client.close()

    def __enter__(self) -> HabitipyClient:
        return self

    def __exit__(self, exc_type: object, exc: object, tb: object) -> Literal[False]:
        self.close()
        return False

    def __repr__(self) -> str:
        return (
            f"{self.__class__.__name__}("
            f"base_url={self._client.base_url!r}, "
            f"timeout={self._client.timeout!r}, "
            f"_owns_client={self._owns_client!r})"
        )

__init__(api_key: str | None = None, *, client: httpx.Client | None = None, base_url: str = DEFAULT_BASE_URL, timeout: float = DEFAULT_TIMEOUT) -> None

Create a new Habitipy client.

Parameters:

Name Type Description Default
api_key str | None

Habitify API key. Required when client is not provided and must be a non-empty string.

None
client Client | None

An existing :class:httpx.Client to use for requests. When provided, the caller is responsible for closing it.

None
base_url str

Base URL for the Habitify API. Defaults to the production v2 endpoint.

DEFAULT_BASE_URL
timeout float

Default timeout in seconds for HTTP requests. Ignored when client is injected.

DEFAULT_TIMEOUT

Raises:

Type Description
ValueError

If api_key is missing, empty, or the injected client lacks the X-API-Key header.

Source code in habitipie/client.py
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
def __init__(
    self,
    api_key: str | None = None,
    *,
    client: httpx.Client | None = None,
    base_url: str = DEFAULT_BASE_URL,
    timeout: float = DEFAULT_TIMEOUT,
) -> None:
    """Create a new Habitipy client.

    Args:
        api_key: Habitify API key. Required when *client* is not provided
            and must be a non-empty string.
        client: An existing :class:`httpx.Client` to use for requests. When
            provided, the caller is responsible for closing it.
        base_url: Base URL for the Habitify API. Defaults to the production
            v2 endpoint.
        timeout: Default timeout in seconds for HTTP requests. Ignored when
            *client* is injected.

    Raises:
        ValueError: If *api_key* is missing, empty, or the injected *client*
            lacks the ``X-API-Key`` header.
    """
    if client is None:
        if api_key is None or api_key == "":
            raise ValueError("api_key is required when client is not provided.")

    self._owns_client = client is None
    default_headers: dict[str, str] | None = None
    if client is None:
        default_headers = {API_KEY_HEADER: cast(str, api_key)}

    self._client = client or httpx.Client(
        base_url=base_url.rstrip("/"),
        timeout=timeout,
        headers=default_headers,
    )

    if client is not None:
        if not str(self._client.base_url):
            self._client.base_url = httpx.URL(base_url.rstrip("/"))

        if api_key is not None and api_key != "":
            self._client.headers[API_KEY_HEADER] = api_key

        if API_KEY_HEADER not in self._client.headers:
            raise ValueError(
                "api_key is required unless the provided client already has "
                f"an {API_KEY_HEADER} header."
            )

    self.habits = HabitsResource(self._client)
    self.areas = AreasResource(self._client)

Resources

Resource namespace for Habitify habits.

Source code in habitipie/habits.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
 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
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
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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
class HabitsResource:
    """Resource namespace for Habitify habits."""

    def __init__(self, client: httpx.Client) -> None:
        self._client = client

    def get(self, habit_id: str) -> Habit:
        """Get a single habit by ID.

        Args:
            habit_id: Unique identifier of the habit.

        Returns:
            The requested :class:`Habit`.

        Raises:
            NotFoundError: If the habit does not exist.
        """
        return request_model(
            self._client,
            "GET",
            f"/habits/{quote_path_value(habit_id)}",
            HabitResponse,
        ).data

    def list(
        self,
        *,
        archived: bool | None = None,
        area_id: str | None = None,
        habit_type: HabitType | None = None,
        time_of_day: str | None = None,
        limit: int | None = None,
        offset: int | None = None,
    ) -> HabitListPage:
        """List habits with optional filtering and pagination.

        Args:
            archived: Filter by archived status.
            area_id: Filter by area ID.
            habit_type: Filter by habit type (``good`` or ``bad``).
            time_of_day: Filter by time-of-day ID.
            limit: Maximum number of items to return (1–100).
            offset: Number of items to skip.

        Returns:
            A :class:`HabitListPage` containing the habits and pagination info.
        """
        params = HabitListParams(
            archived=archived,
            area_id=area_id,
            habit_type=habit_type,
            time_of_day=time_of_day,
            limit=limit,
            offset=offset,
        )
        return request_model(
            self._client,
            "GET",
            "/habits",
            HabitListPage,
            params=params.to_query_params(),
        )

    def create(self, request: HabitCreateRequest) -> Habit:
        """Create a new habit.

        Args:
            request: Habit creation payload.

        Returns:
            The newly created :class:`Habit`.
        """
        return request_model(
            self._client,
            "POST",
            "/habits",
            HabitResponse,
            json=request.to_request_body(),
        ).data

    def archive(self, habit_id: str) -> None:
        """Archive a habit.

        Args:
            habit_id: Unique identifier of the habit to archive.

        Raises:
            NotFoundError: If the habit does not exist.
            ApiError: If the habit is already archived.
        """
        request_no_content(
            self._client,
            "POST",
            f"/habits/{quote_path_value(habit_id)}/archive",
            success_label="habit archive",
        )

    def delete(self, habit_id: str) -> None:
        """Delete a habit.

        Args:
            habit_id: Unique identifier of the habit to delete.

        Raises:
            NotFoundError: If the habit does not exist.
        """
        request_no_content(
            self._client,
            "DELETE",
            f"/habits/{quote_path_value(habit_id)}",
            success_label="habit deletion",
        )

    def create_log(self, habit_id: str, request: HabitLogRequest) -> HabitLogResponse:
        """Create a log entry for a habit.

        Args:
            habit_id: Unique identifier of the habit.
            request: Log creation payload.

        Returns:
            A :class:`HabitLogResponse` confirming the log was created.

        Raises:
            NotFoundError: If the habit does not exist.
            ApiError: If the request payload is invalid.
        """
        return request_model(
            self._client,
            "POST",
            f"/habits/{quote_path_value(habit_id)}/logs",
            HabitLogResponse,
            json=request.to_request_body(),
        )

    def delete_log(self, habit_id: str, log_id: str) -> SuccessMessageResponse:
        """Delete a log entry.

        Args:
            habit_id: Unique identifier of the habit.
            log_id: Unique identifier of the log entry.

        Returns:
            A :class:`SuccessMessageResponse` confirming the deletion.

        Raises:
            NotFoundError: If the habit or log entry does not exist.
        """
        return request_model(
            self._client,
            "DELETE",
            f"/habits/{quote_path_value(habit_id)}/logs/{quote_path_value(log_id)}",
            SuccessMessageResponse,
        )

    def complete_log(
        self,
        habit_id: str,
        request: HabitLogActionRequest | None = None,
    ) -> SuccessMessageResponse:
        """Mark a habit as completed for a given date.

        Args:
            habit_id: Unique identifier of the habit.
            request: Optional payload with the target date.

        Returns:
            A :class:`SuccessMessageResponse` confirming the action.
        """
        return self._post_log_action(habit_id, "complete", request)

    def fail_log(
        self,
        habit_id: str,
        request: HabitLogActionRequest | None = None,
    ) -> SuccessMessageResponse:
        """Mark a habit as failed for a given date.

        Args:
            habit_id: Unique identifier of the habit.
            request: Optional payload with the target date.

        Returns:
            A :class:`SuccessMessageResponse` confirming the action.
        """
        return self._post_log_action(habit_id, "failed", request)

    def skip_log(
        self,
        habit_id: str,
        request: HabitLogActionRequest | None = None,
    ) -> SuccessMessageResponse:
        """Mark a habit as skipped for a given date.

        Args:
            habit_id: Unique identifier of the habit.
            request: Optional payload with the target date.

        Returns:
            A :class:`SuccessMessageResponse` confirming the action.
        """
        return self._post_log_action(habit_id, "skipped", request)

    def undo_log(
        self,
        habit_id: str,
        request: HabitLogActionRequest | None = None,
    ) -> SuccessMessageResponse:
        """Undo the most recent log action for a habit.

        Args:
            habit_id: Unique identifier of the habit.
            request: Optional payload with the target date.

        Returns:
            A :class:`SuccessMessageResponse` confirming the action.
        """
        return self._post_log_action(habit_id, "undo", request)

    def list_notes(self, habit_id: str) -> builtins.list[HabitNote]:
        """List all notes for a habit.

        Args:
            habit_id: Unique identifier of the habit.

        Returns:
            List of :class:`HabitNote` objects.

        Raises:
            NotFoundError: If the habit does not exist.
        """
        return request_model(
            self._client,
            "GET",
            f"/habits/{quote_path_value(habit_id)}/notes",
            HabitNoteListResponse,
        ).data

    def create_note(self, habit_id: str, request: HabitNoteCreateRequest) -> HabitNote:
        """Create a note for a habit.

        Args:
            habit_id: Unique identifier of the habit.
            request: Note creation payload.

        Returns:
            The newly created :class:`HabitNote`.

        Raises:
            NotFoundError: If the habit does not exist.
        """
        return request_model(
            self._client,
            "POST",
            f"/habits/{quote_path_value(habit_id)}/notes",
            HabitNote,
            json=request.to_request_body(),
        )

    def update_note(
        self,
        habit_id: str,
        note_id: str,
        request: HabitNoteUpdateRequest,
    ) -> HabitNote:
        """Update an existing note.

        Args:
            habit_id: Unique identifier of the habit.
            note_id: Unique identifier of the note.
            request: Note update payload.

        Returns:
            The updated :class:`HabitNote`.

        Raises:
            NotFoundError: If the habit or note does not exist.
        """
        return request_model(
            self._client,
            "PUT",
            f"/habits/{quote_path_value(habit_id)}/notes/{quote_path_value(note_id)}",
            HabitNote,
            json=request.to_request_body(),
        )

    def delete_note(self, habit_id: str, note_id: str) -> None:
        """Delete a note.

        Args:
            habit_id: Unique identifier of the habit.
            note_id: Unique identifier of the note.

        Raises:
            NotFoundError: If the habit or note does not exist.
        """
        request_no_content(
            self._client,
            "DELETE",
            f"/habits/{quote_path_value(habit_id)}/notes/{quote_path_value(note_id)}",
            success_label="habit note deletion",
        )

    def update(self, habit_id: str, request: HabitUpdateRequest) -> Habit:
        """Update an existing habit.

        Args:
            habit_id: Unique identifier of the habit to update.
            request: Habit update payload.

        Returns:
            The updated :class:`Habit`.

        Raises:
            NotFoundError: If the habit does not exist.
            ApiError: If the request payload is invalid.
        """
        return request_model(
            self._client,
            "PUT",
            f"/habits/{quote_path_value(habit_id)}",
            HabitResponse,
            json=request.to_request_body(),
        ).data

    def journal(self, *, journal_date: date | None = None) -> builtins.list[HabitJournalEntry]:
        """Fetch the habit journal for a specific date.

        Args:
            journal_date: Date to fetch the journal for. Defaults to today.

        Returns:
            List of :class:`HabitJournalEntry` objects.
        """
        params = HabitJournalParams(journal_date=journal_date)
        return request_model(
            self._client,
            "GET",
            "/habits/journal",
            HabitJournalPage,
            params=params.to_query_params(),
        ).data

    def statistics(
        self,
        habit_id: str,
        *,
        start_date: date | None = None,
        end_date: date | None = None,
    ) -> HabitStatistics:
        """Fetch statistics for a habit.

        Args:
            habit_id: Unique identifier of the habit.
            start_date: Start of the date range (inclusive).
            end_date: End of the date range (inclusive).

        Returns:
            A :class:`HabitStatistics` object.

        Raises:
            NotFoundError: If the habit does not exist.
            ApiError: If the date range is invalid.
        """
        params = HabitStatisticsParams(start_date=start_date, end_date=end_date)
        return request_model(
            self._client,
            "GET",
            f"/habits/{quote_path_value(habit_id)}/statistics",
            HabitStatisticsResponse,
            params=params.to_query_params(),
        ).data

    def _post_log_action(
        self,
        habit_id: str,
        action: str,
        request: HabitLogActionRequest | None,
    ) -> SuccessMessageResponse:
        """Internal helper to POST a log action endpoint."""
        request_body = request.to_request_body() if request is not None else None
        return request_model(
            self._client,
            "POST",
            f"/habits/{quote_path_value(habit_id)}/logs/{action}",
            SuccessMessageResponse,
            json=request_body,
        )

get(habit_id: str) -> Habit

Get a single habit by ID.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required

Returns:

Type Description
Habit

The requested :class:Habit.

Raises:

Type Description
NotFoundError

If the habit does not exist.

Source code in habitipie/habits.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def get(self, habit_id: str) -> Habit:
    """Get a single habit by ID.

    Args:
        habit_id: Unique identifier of the habit.

    Returns:
        The requested :class:`Habit`.

    Raises:
        NotFoundError: If the habit does not exist.
    """
    return request_model(
        self._client,
        "GET",
        f"/habits/{quote_path_value(habit_id)}",
        HabitResponse,
    ).data

list(*, archived: bool | None = None, area_id: str | None = None, habit_type: HabitType | None = None, time_of_day: str | None = None, limit: int | None = None, offset: int | None = None) -> HabitListPage

List habits with optional filtering and pagination.

Parameters:

Name Type Description Default
archived bool | None

Filter by archived status.

None
area_id str | None

Filter by area ID.

None
habit_type HabitType | None

Filter by habit type (good or bad).

None
time_of_day str | None

Filter by time-of-day ID.

None
limit int | None

Maximum number of items to return (1–100).

None
offset int | None

Number of items to skip.

None

Returns:

Name Type Description
A HabitListPage

class:HabitListPage containing the habits and pagination info.

Source code in habitipie/habits.py
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
def list(
    self,
    *,
    archived: bool | None = None,
    area_id: str | None = None,
    habit_type: HabitType | None = None,
    time_of_day: str | None = None,
    limit: int | None = None,
    offset: int | None = None,
) -> HabitListPage:
    """List habits with optional filtering and pagination.

    Args:
        archived: Filter by archived status.
        area_id: Filter by area ID.
        habit_type: Filter by habit type (``good`` or ``bad``).
        time_of_day: Filter by time-of-day ID.
        limit: Maximum number of items to return (1–100).
        offset: Number of items to skip.

    Returns:
        A :class:`HabitListPage` containing the habits and pagination info.
    """
    params = HabitListParams(
        archived=archived,
        area_id=area_id,
        habit_type=habit_type,
        time_of_day=time_of_day,
        limit=limit,
        offset=offset,
    )
    return request_model(
        self._client,
        "GET",
        "/habits",
        HabitListPage,
        params=params.to_query_params(),
    )

create(request: HabitCreateRequest) -> Habit

Create a new habit.

Parameters:

Name Type Description Default
request HabitCreateRequest

Habit creation payload.

required

Returns:

Type Description
Habit

The newly created :class:Habit.

Source code in habitipie/habits.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def create(self, request: HabitCreateRequest) -> Habit:
    """Create a new habit.

    Args:
        request: Habit creation payload.

    Returns:
        The newly created :class:`Habit`.
    """
    return request_model(
        self._client,
        "POST",
        "/habits",
        HabitResponse,
        json=request.to_request_body(),
    ).data

archive(habit_id: str) -> None

Archive a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit to archive.

required

Raises:

Type Description
NotFoundError

If the habit does not exist.

ApiError

If the habit is already archived.

Source code in habitipie/habits.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def archive(self, habit_id: str) -> None:
    """Archive a habit.

    Args:
        habit_id: Unique identifier of the habit to archive.

    Raises:
        NotFoundError: If the habit does not exist.
        ApiError: If the habit is already archived.
    """
    request_no_content(
        self._client,
        "POST",
        f"/habits/{quote_path_value(habit_id)}/archive",
        success_label="habit archive",
    )

delete(habit_id: str) -> None

Delete a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit to delete.

required

Raises:

Type Description
NotFoundError

If the habit does not exist.

Source code in habitipie/habits.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def delete(self, habit_id: str) -> None:
    """Delete a habit.

    Args:
        habit_id: Unique identifier of the habit to delete.

    Raises:
        NotFoundError: If the habit does not exist.
    """
    request_no_content(
        self._client,
        "DELETE",
        f"/habits/{quote_path_value(habit_id)}",
        success_label="habit deletion",
    )

create_log(habit_id: str, request: HabitLogRequest) -> HabitLogResponse

Create a log entry for a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
request HabitLogRequest

Log creation payload.

required

Returns:

Name Type Description
A HabitLogResponse

class:HabitLogResponse confirming the log was created.

Raises:

Type Description
NotFoundError

If the habit does not exist.

ApiError

If the request payload is invalid.

Source code in habitipie/habits.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def create_log(self, habit_id: str, request: HabitLogRequest) -> HabitLogResponse:
    """Create a log entry for a habit.

    Args:
        habit_id: Unique identifier of the habit.
        request: Log creation payload.

    Returns:
        A :class:`HabitLogResponse` confirming the log was created.

    Raises:
        NotFoundError: If the habit does not exist.
        ApiError: If the request payload is invalid.
    """
    return request_model(
        self._client,
        "POST",
        f"/habits/{quote_path_value(habit_id)}/logs",
        HabitLogResponse,
        json=request.to_request_body(),
    )

delete_log(habit_id: str, log_id: str) -> SuccessMessageResponse

Delete a log entry.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
log_id str

Unique identifier of the log entry.

required

Returns:

Name Type Description
A SuccessMessageResponse

class:SuccessMessageResponse confirming the deletion.

Raises:

Type Description
NotFoundError

If the habit or log entry does not exist.

Source code in habitipie/habits.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def delete_log(self, habit_id: str, log_id: str) -> SuccessMessageResponse:
    """Delete a log entry.

    Args:
        habit_id: Unique identifier of the habit.
        log_id: Unique identifier of the log entry.

    Returns:
        A :class:`SuccessMessageResponse` confirming the deletion.

    Raises:
        NotFoundError: If the habit or log entry does not exist.
    """
    return request_model(
        self._client,
        "DELETE",
        f"/habits/{quote_path_value(habit_id)}/logs/{quote_path_value(log_id)}",
        SuccessMessageResponse,
    )

complete_log(habit_id: str, request: HabitLogActionRequest | None = None) -> SuccessMessageResponse

Mark a habit as completed for a given date.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
request HabitLogActionRequest | None

Optional payload with the target date.

None

Returns:

Name Type Description
A SuccessMessageResponse

class:SuccessMessageResponse confirming the action.

Source code in habitipie/habits.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def complete_log(
    self,
    habit_id: str,
    request: HabitLogActionRequest | None = None,
) -> SuccessMessageResponse:
    """Mark a habit as completed for a given date.

    Args:
        habit_id: Unique identifier of the habit.
        request: Optional payload with the target date.

    Returns:
        A :class:`SuccessMessageResponse` confirming the action.
    """
    return self._post_log_action(habit_id, "complete", request)

fail_log(habit_id: str, request: HabitLogActionRequest | None = None) -> SuccessMessageResponse

Mark a habit as failed for a given date.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
request HabitLogActionRequest | None

Optional payload with the target date.

None

Returns:

Name Type Description
A SuccessMessageResponse

class:SuccessMessageResponse confirming the action.

Source code in habitipie/habits.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def fail_log(
    self,
    habit_id: str,
    request: HabitLogActionRequest | None = None,
) -> SuccessMessageResponse:
    """Mark a habit as failed for a given date.

    Args:
        habit_id: Unique identifier of the habit.
        request: Optional payload with the target date.

    Returns:
        A :class:`SuccessMessageResponse` confirming the action.
    """
    return self._post_log_action(habit_id, "failed", request)

skip_log(habit_id: str, request: HabitLogActionRequest | None = None) -> SuccessMessageResponse

Mark a habit as skipped for a given date.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
request HabitLogActionRequest | None

Optional payload with the target date.

None

Returns:

Name Type Description
A SuccessMessageResponse

class:SuccessMessageResponse confirming the action.

Source code in habitipie/habits.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def skip_log(
    self,
    habit_id: str,
    request: HabitLogActionRequest | None = None,
) -> SuccessMessageResponse:
    """Mark a habit as skipped for a given date.

    Args:
        habit_id: Unique identifier of the habit.
        request: Optional payload with the target date.

    Returns:
        A :class:`SuccessMessageResponse` confirming the action.
    """
    return self._post_log_action(habit_id, "skipped", request)

undo_log(habit_id: str, request: HabitLogActionRequest | None = None) -> SuccessMessageResponse

Undo the most recent log action for a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
request HabitLogActionRequest | None

Optional payload with the target date.

None

Returns:

Name Type Description
A SuccessMessageResponse

class:SuccessMessageResponse confirming the action.

Source code in habitipie/habits.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def undo_log(
    self,
    habit_id: str,
    request: HabitLogActionRequest | None = None,
) -> SuccessMessageResponse:
    """Undo the most recent log action for a habit.

    Args:
        habit_id: Unique identifier of the habit.
        request: Optional payload with the target date.

    Returns:
        A :class:`SuccessMessageResponse` confirming the action.
    """
    return self._post_log_action(habit_id, "undo", request)

list_notes(habit_id: str) -> builtins.list[HabitNote]

List all notes for a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required

Returns:

Type Description
list[HabitNote]

List of :class:HabitNote objects.

Raises:

Type Description
NotFoundError

If the habit does not exist.

Source code in habitipie/habits.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def list_notes(self, habit_id: str) -> builtins.list[HabitNote]:
    """List all notes for a habit.

    Args:
        habit_id: Unique identifier of the habit.

    Returns:
        List of :class:`HabitNote` objects.

    Raises:
        NotFoundError: If the habit does not exist.
    """
    return request_model(
        self._client,
        "GET",
        f"/habits/{quote_path_value(habit_id)}/notes",
        HabitNoteListResponse,
    ).data

create_note(habit_id: str, request: HabitNoteCreateRequest) -> HabitNote

Create a note for a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
request HabitNoteCreateRequest

Note creation payload.

required

Returns:

Type Description
HabitNote

The newly created :class:HabitNote.

Raises:

Type Description
NotFoundError

If the habit does not exist.

Source code in habitipie/habits.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def create_note(self, habit_id: str, request: HabitNoteCreateRequest) -> HabitNote:
    """Create a note for a habit.

    Args:
        habit_id: Unique identifier of the habit.
        request: Note creation payload.

    Returns:
        The newly created :class:`HabitNote`.

    Raises:
        NotFoundError: If the habit does not exist.
    """
    return request_model(
        self._client,
        "POST",
        f"/habits/{quote_path_value(habit_id)}/notes",
        HabitNote,
        json=request.to_request_body(),
    )

update_note(habit_id: str, note_id: str, request: HabitNoteUpdateRequest) -> HabitNote

Update an existing note.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
note_id str

Unique identifier of the note.

required
request HabitNoteUpdateRequest

Note update payload.

required

Returns:

Type Description
HabitNote

The updated :class:HabitNote.

Raises:

Type Description
NotFoundError

If the habit or note does not exist.

Source code in habitipie/habits.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
def update_note(
    self,
    habit_id: str,
    note_id: str,
    request: HabitNoteUpdateRequest,
) -> HabitNote:
    """Update an existing note.

    Args:
        habit_id: Unique identifier of the habit.
        note_id: Unique identifier of the note.
        request: Note update payload.

    Returns:
        The updated :class:`HabitNote`.

    Raises:
        NotFoundError: If the habit or note does not exist.
    """
    return request_model(
        self._client,
        "PUT",
        f"/habits/{quote_path_value(habit_id)}/notes/{quote_path_value(note_id)}",
        HabitNote,
        json=request.to_request_body(),
    )

delete_note(habit_id: str, note_id: str) -> None

Delete a note.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
note_id str

Unique identifier of the note.

required

Raises:

Type Description
NotFoundError

If the habit or note does not exist.

Source code in habitipie/habits.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def delete_note(self, habit_id: str, note_id: str) -> None:
    """Delete a note.

    Args:
        habit_id: Unique identifier of the habit.
        note_id: Unique identifier of the note.

    Raises:
        NotFoundError: If the habit or note does not exist.
    """
    request_no_content(
        self._client,
        "DELETE",
        f"/habits/{quote_path_value(habit_id)}/notes/{quote_path_value(note_id)}",
        success_label="habit note deletion",
    )

update(habit_id: str, request: HabitUpdateRequest) -> Habit

Update an existing habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit to update.

required
request HabitUpdateRequest

Habit update payload.

required

Returns:

Type Description
Habit

The updated :class:Habit.

Raises:

Type Description
NotFoundError

If the habit does not exist.

ApiError

If the request payload is invalid.

Source code in habitipie/habits.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def update(self, habit_id: str, request: HabitUpdateRequest) -> Habit:
    """Update an existing habit.

    Args:
        habit_id: Unique identifier of the habit to update.
        request: Habit update payload.

    Returns:
        The updated :class:`Habit`.

    Raises:
        NotFoundError: If the habit does not exist.
        ApiError: If the request payload is invalid.
    """
    return request_model(
        self._client,
        "PUT",
        f"/habits/{quote_path_value(habit_id)}",
        HabitResponse,
        json=request.to_request_body(),
    ).data

journal(*, journal_date: date | None = None) -> builtins.list[HabitJournalEntry]

Fetch the habit journal for a specific date.

Parameters:

Name Type Description Default
journal_date date | None

Date to fetch the journal for. Defaults to today.

None

Returns:

Type Description
list[HabitJournalEntry]

List of :class:HabitJournalEntry objects.

Source code in habitipie/habits.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def journal(self, *, journal_date: date | None = None) -> builtins.list[HabitJournalEntry]:
    """Fetch the habit journal for a specific date.

    Args:
        journal_date: Date to fetch the journal for. Defaults to today.

    Returns:
        List of :class:`HabitJournalEntry` objects.
    """
    params = HabitJournalParams(journal_date=journal_date)
    return request_model(
        self._client,
        "GET",
        "/habits/journal",
        HabitJournalPage,
        params=params.to_query_params(),
    ).data

statistics(habit_id: str, *, start_date: date | None = None, end_date: date | None = None) -> HabitStatistics

Fetch statistics for a habit.

Parameters:

Name Type Description Default
habit_id str

Unique identifier of the habit.

required
start_date date | None

Start of the date range (inclusive).

None
end_date date | None

End of the date range (inclusive).

None

Returns:

Name Type Description
A HabitStatistics

class:HabitStatistics object.

Raises:

Type Description
NotFoundError

If the habit does not exist.

ApiError

If the date range is invalid.

Source code in habitipie/habits.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def statistics(
    self,
    habit_id: str,
    *,
    start_date: date | None = None,
    end_date: date | None = None,
) -> HabitStatistics:
    """Fetch statistics for a habit.

    Args:
        habit_id: Unique identifier of the habit.
        start_date: Start of the date range (inclusive).
        end_date: End of the date range (inclusive).

    Returns:
        A :class:`HabitStatistics` object.

    Raises:
        NotFoundError: If the habit does not exist.
        ApiError: If the date range is invalid.
    """
    params = HabitStatisticsParams(start_date=start_date, end_date=end_date)
    return request_model(
        self._client,
        "GET",
        f"/habits/{quote_path_value(habit_id)}/statistics",
        HabitStatisticsResponse,
        params=params.to_query_params(),
    ).data

Resource namespace for Habitify areas.

Source code in habitipie/areas.py
 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
 98
 99
100
class AreasResource:
    """Resource namespace for Habitify areas."""

    def __init__(self, client: httpx.Client) -> None:
        self._client = client

    def list(self) -> list[Area]:
        """List all areas.

        Returns:
            List of :class:`Area` objects.
        """
        return request_model(self._client, "GET", "/areas", AreaListResponse).data

    def get(self, area_id: str) -> Area:
        """Get a single area by ID.

        Args:
            area_id: Unique identifier of the area.

        Returns:
            The requested :class:`Area`.

        Raises:
            NotFoundError: If the area does not exist.
        """
        return request_model(
            self._client,
            "GET",
            f"/areas/{quote_path_value(area_id)}",
            AreaResponse,
        ).data

    def create(self, request: AreaCreateRequest) -> Area:
        """Create a new area.

        Args:
            request: Area creation payload.

        Returns:
            The newly created :class:`Area`.
        """
        return request_model(
            self._client,
            "POST",
            "/areas",
            AreaResponse,
            json=request.to_request_body(),
        ).data

    def update(self, area_id: str, request: AreaUpdateRequest) -> Area:
        """Update an existing area.

        Args:
            area_id: Unique identifier of the area to update.
            request: Area update payload.

        Returns:
            The updated :class:`Area`.

        Raises:
            NotFoundError: If the area does not exist.
        """
        return request_model(
            self._client,
            "PUT",
            f"/areas/{quote_path_value(area_id)}",
            AreaResponse,
            json=request.to_request_body(),
        ).data

    def delete(self, area_id: str) -> None:
        """Delete an area.

        Args:
            area_id: Unique identifier of the area to delete.

        Raises:
            NotFoundError: If the area does not exist.
        """
        request_no_content(
            self._client,
            "DELETE",
            f"/areas/{quote_path_value(area_id)}",
            success_label="area deletion",
        )

list() -> list[Area]

List all areas.

Returns:

Type Description
list[Area]

List of :class:Area objects.

Source code in habitipie/areas.py
21
22
23
24
25
26
27
def list(self) -> list[Area]:
    """List all areas.

    Returns:
        List of :class:`Area` objects.
    """
    return request_model(self._client, "GET", "/areas", AreaListResponse).data

get(area_id: str) -> Area

Get a single area by ID.

Parameters:

Name Type Description Default
area_id str

Unique identifier of the area.

required

Returns:

Type Description
Area

The requested :class:Area.

Raises:

Type Description
NotFoundError

If the area does not exist.

Source code in habitipie/areas.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def get(self, area_id: str) -> Area:
    """Get a single area by ID.

    Args:
        area_id: Unique identifier of the area.

    Returns:
        The requested :class:`Area`.

    Raises:
        NotFoundError: If the area does not exist.
    """
    return request_model(
        self._client,
        "GET",
        f"/areas/{quote_path_value(area_id)}",
        AreaResponse,
    ).data

create(request: AreaCreateRequest) -> Area

Create a new area.

Parameters:

Name Type Description Default
request AreaCreateRequest

Area creation payload.

required

Returns:

Type Description
Area

The newly created :class:Area.

Source code in habitipie/areas.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def create(self, request: AreaCreateRequest) -> Area:
    """Create a new area.

    Args:
        request: Area creation payload.

    Returns:
        The newly created :class:`Area`.
    """
    return request_model(
        self._client,
        "POST",
        "/areas",
        AreaResponse,
        json=request.to_request_body(),
    ).data

update(area_id: str, request: AreaUpdateRequest) -> Area

Update an existing area.

Parameters:

Name Type Description Default
area_id str

Unique identifier of the area to update.

required
request AreaUpdateRequest

Area update payload.

required

Returns:

Type Description
Area

The updated :class:Area.

Raises:

Type Description
NotFoundError

If the area does not exist.

Source code in habitipie/areas.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def update(self, area_id: str, request: AreaUpdateRequest) -> Area:
    """Update an existing area.

    Args:
        area_id: Unique identifier of the area to update.
        request: Area update payload.

    Returns:
        The updated :class:`Area`.

    Raises:
        NotFoundError: If the area does not exist.
    """
    return request_model(
        self._client,
        "PUT",
        f"/areas/{quote_path_value(area_id)}",
        AreaResponse,
        json=request.to_request_body(),
    ).data

delete(area_id: str) -> None

Delete an area.

Parameters:

Name Type Description Default
area_id str

Unique identifier of the area to delete.

required

Raises:

Type Description
NotFoundError

If the area does not exist.

Source code in habitipie/areas.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def delete(self, area_id: str) -> None:
    """Delete an area.

    Args:
        area_id: Unique identifier of the area to delete.

    Raises:
        NotFoundError: If the area does not exist.
    """
    request_no_content(
        self._client,
        "DELETE",
        f"/areas/{quote_path_value(area_id)}",
        success_label="area deletion",
    )

Models

HabitipyBaseModel

Bases: BaseModel

Base model for all Habitify API data structures.

Uses extra="ignore" so unknown fields in server responses are silently discarded rather than causing validation errors.

Source code in habitipie/models/habits.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class HabitipyBaseModel(BaseModel):
    """Base model for all Habitify API data structures.

    Uses ``extra="ignore"`` so unknown fields in server responses are silently
    discarded rather than causing validation errors.
    """

    model_config = ConfigDict(extra="ignore", populate_by_name=True)

    def to_request_body(self) -> dict[str, object]:
        return cast(
            dict[str, object],
            self.model_dump(by_alias=True, exclude_none=True, mode="json"),
        )

    def to_query_params(self) -> dict[str, str]:
        serialized: dict[str, str] = {}
        for key, value in self.model_dump(by_alias=True, exclude_none=True, mode="json").items():
            if isinstance(value, bool):
                serialized[key] = str(value).lower()
            else:
                serialized[key] = str(value)
        return serialized

HabitipyRequestModel

Bases: HabitipyBaseModel

Base for request payloads sent to the Habitify API.

Uses extra="forbid" so typos in field names or unexpected keys raise a validation error at model construction time rather than being silently dropped by the server.

Source code in habitipie/models/habits.py
37
38
39
40
41
42
43
44
45
class HabitipyRequestModel(HabitipyBaseModel):
    """Base for request payloads sent to the Habitify API.

    Uses ``extra="forbid"`` so typos in field names or unexpected keys raise
    a validation error at model construction time rather than being silently
    dropped by the server.
    """

    model_config = ConfigDict(extra="forbid", populate_by_name=True)

HabitType

Bases: str, Enum

Classification of a habit's moral direction.

Source code in habitipie/models/habits.py
65
66
67
68
69
class HabitType(str, Enum):
    """Classification of a habit's moral direction."""

    GOOD = "good"
    BAD = "bad"

LogMethod

Bases: str, Enum

How a habit log entry was recorded.

Source code in habitipie/models/habits.py
72
73
74
75
76
class LogMethod(str, Enum):
    """How a habit log entry was recorded."""

    MANUAL = "manual"
    AUTO = "auto"

GoalPeriodicity

Bases: str, Enum

Time window for evaluating a habit's goal.

Source code in habitipie/models/habits.py
79
80
81
82
83
84
85
class GoalPeriodicity(str, Enum):
    """Time window for evaluating a habit's goal."""

    DAILY = "daily"
    WEEKLY = "weekly"
    MONTHLY = "monthly"
    YEARLY = "yearly"

HabitStackTriggerType

Bases: str, Enum

Event that triggers a habit stack action.

Source code in habitipie/models/habits.py
117
118
119
120
121
122
123
class HabitStackTriggerType(str, Enum):
    """Event that triggers a habit stack action."""

    COMPLETED = "completed"
    SKIPPED = "skipped"
    FAILED = "failed"
    REMINDER = "reminder"

HabitStackTimerType

Bases: str, Enum

Timing mode for a habit stack trigger.

Source code in habitipie/models/habits.py
126
127
128
129
130
class HabitStackTimerType(str, Enum):
    """Timing mode for a habit stack trigger."""

    IMMEDIATELY = "immediately"
    AFTER = "after"

ReminderTime

Bases: HabitipyBaseModel

Clock time for a reminder notification.

Source code in habitipie/models/habits.py
133
134
135
136
137
class ReminderTime(HabitipyBaseModel):
    """Clock time for a reminder notification."""

    hour: int
    minute: int

ReminderOccurrenceFilter

Bases: HabitipyBaseModel

Optional filter limiting which days a reminder fires.

Source code in habitipie/models/habits.py
140
141
142
143
class ReminderOccurrenceFilter(HabitipyBaseModel):
    """Optional filter limiting which days a reminder fires."""

    week_days: list[int] | None = Field(default=None, alias="weekDays")

TimeTrigger

Bases: HabitipyBaseModel

A single reminder tied to a specific clock time.

Source code in habitipie/models/habits.py
146
147
148
149
150
151
152
153
154
class TimeTrigger(HabitipyBaseModel):
    """A single reminder tied to a specific clock time."""

    time: ReminderTime
    occurrence_filter: ReminderOccurrenceFilter | None = Field(
        default=None, alias="occurrenceFilter"
    )
    show_live_activity: bool | None = Field(default=None, alias="showLiveActivity")
    show_as_alarm: bool | None = Field(default=None, alias="showAsAlarm")

HabitStack

Bases: HabitipyBaseModel

Chain reaction triggered by another habit's state change.

Source code in habitipie/models/habits.py
157
158
159
160
161
162
163
164
class HabitStack(HabitipyBaseModel):
    """Chain reaction triggered by another habit's state change."""

    id: str | None = None
    condition_habit_id: str = Field(alias="conditionHabitId")
    type: HabitStackTriggerType
    timer_type: HabitStackTimerType = Field(alias="timerType")
    timer_delay_secs: int | None = Field(default=None, alias="timerDelaySecs")

DailyOccurrence

Bases: HabitipyBaseModel

Occurs every day.

Source code in habitipie/models/habits.py
188
189
190
191
class DailyOccurrence(HabitipyBaseModel):
    """Occurs every day."""

    type: Literal["daily"]

WeekDaysOccurrence

Bases: HabitipyBaseModel

Occurs on specific days of the week (0=Sunday).

Source code in habitipie/models/habits.py
194
195
196
197
198
class WeekDaysOccurrence(HabitipyBaseModel):
    """Occurs on specific days of the week (0=Sunday)."""

    type: Literal["weekDays"]
    days: list[int]

MonthDaysOccurrence

Bases: HabitipyBaseModel

Occurs on specific days of the month.

Source code in habitipie/models/habits.py
201
202
203
204
205
class MonthDaysOccurrence(HabitipyBaseModel):
    """Occurs on specific days of the month."""

    type: Literal["monthDays"]
    days: list[int]

IntervalDaysOccurrence

Bases: HabitipyBaseModel

Occurs every N days.

Source code in habitipie/models/habits.py
208
209
210
211
212
class IntervalDaysOccurrence(HabitipyBaseModel):
    """Occurs every N days."""

    type: Literal["intervalDays"]
    interval: int

DateEndCondition

Bases: HabitipyBaseModel

End condition satisfied on a specific calendar date.

Source code in habitipie/models/habits.py
233
234
235
236
237
238
239
240
class DateEndCondition(HabitipyBaseModel):
    """End condition satisfied on a specific calendar date."""

    id: str
    type: Literal["date"]
    created_at: datetime = Field(alias="createdAt")
    is_met: bool = Field(alias="isMet")
    date: date

StreakEndCondition

Bases: HabitipyBaseModel

End condition satisfied after maintaining a streak for a given length.

Source code in habitipie/models/habits.py
243
244
245
246
247
248
249
250
251
class StreakEndCondition(HabitipyBaseModel):
    """End condition satisfied after maintaining a streak for a given length."""

    id: str
    type: Literal["streak"]
    created_at: datetime = Field(alias="createdAt")
    is_met: bool = Field(alias="isMet")
    period_type: GoalPeriodicity = Field(alias="periodType")
    streak_length: int = Field(alias="streakLength")

SuccessPeriodsEndCondition

Bases: HabitipyBaseModel

End condition satisfied after completing a number of goal periods.

Source code in habitipie/models/habits.py
254
255
256
257
258
259
260
261
262
class SuccessPeriodsEndCondition(HabitipyBaseModel):
    """End condition satisfied after completing a number of goal periods."""

    id: str
    type: Literal["successPeriods"]
    created_at: datetime = Field(alias="createdAt")
    is_met: bool = Field(alias="isMet")
    period_type: GoalPeriodicity = Field(alias="periodType")
    total_periods: int = Field(alias="totalPeriods")

TotalLogValueEndCondition

Bases: HabitipyBaseModel

End condition satisfied after accumulating a total log value.

Source code in habitipie/models/habits.py
265
266
267
268
269
270
271
272
class TotalLogValueEndCondition(HabitipyBaseModel):
    """End condition satisfied after accumulating a total log value."""

    id: str
    type: Literal["totalLogValue"]
    created_at: datetime = Field(alias="createdAt")
    is_met: bool = Field(alias="isMet")
    total_log_value: float = Field(alias="totalLogValue")

HabitCreateDateEndCondition

Bases: HabitipyBaseModel

Request payload for a date-based end condition.

Source code in habitipie/models/habits.py
275
276
277
278
279
class HabitCreateDateEndCondition(HabitipyBaseModel):
    """Request payload for a date-based end condition."""

    type: Literal["date"]
    date: date

HabitCreateStreakEndCondition

Bases: HabitipyBaseModel

Request payload for a streak-based end condition.

Source code in habitipie/models/habits.py
282
283
284
285
286
class HabitCreateStreakEndCondition(HabitipyBaseModel):
    """Request payload for a streak-based end condition."""

    type: Literal["streak"]
    streak_length: int = Field(alias="streakLength")

HabitCreateSuccessPeriodsEndCondition

Bases: HabitipyBaseModel

Request payload for a success-periods end condition.

Source code in habitipie/models/habits.py
289
290
291
292
293
class HabitCreateSuccessPeriodsEndCondition(HabitipyBaseModel):
    """Request payload for a success-periods end condition."""

    type: Literal["successPeriods"]
    total_periods: int = Field(alias="totalPeriods")

HabitCreateTotalLogValueEndCondition

Bases: HabitipyBaseModel

Request payload for a total-log-value end condition.

Source code in habitipie/models/habits.py
296
297
298
299
300
class HabitCreateTotalLogValueEndCondition(HabitipyBaseModel):
    """Request payload for a total-log-value end condition."""

    type: Literal["totalLogValue"]
    total_log_value: float = Field(alias="totalLogValue")

HabitCreateGoal

Bases: HabitipyRequestModel

Goal definition used when creating a new habit.

Source code in habitipie/models/habits.py
318
319
320
321
322
323
class HabitCreateGoal(HabitipyRequestModel):
    """Goal definition used when creating a new habit."""

    periodicity: GoalPeriodicity
    value: float
    unit: UnitSymbol

Goal

Bases: HabitipyBaseModel

Goal returned by the API, including server-generated metadata.

Source code in habitipie/models/habits.py
326
327
328
329
330
331
332
333
334
class Goal(HabitipyBaseModel):
    """Goal returned by the API, including server-generated metadata."""

    id: str
    created_at: datetime = Field(alias="createdAt")
    periodicity: GoalPeriodicity
    value: float
    unit: UnitSymbol
    is_active: bool | None = Field(default=None, alias="isActive")

Area

Bases: HabitipyBaseModel

A named area (category) that habits can belong to.

Source code in habitipie/models/habits.py
337
338
339
340
341
342
343
344
345
class Area(HabitipyBaseModel):
    """A named area (category) that habits can belong to."""

    id: str
    name: str
    color_hex: str | None = Field(default=None, alias="colorHex")
    icon: str | None = None
    created_at: datetime = Field(alias="createdAt")
    description: str | None = None

AreaResponse

Bases: HabitipyBaseModel

Single-area response envelope.

Source code in habitipie/models/habits.py
348
349
350
351
class AreaResponse(HabitipyBaseModel):
    """Single-area response envelope."""

    data: Area

AreaListResponse

Bases: HabitipyBaseModel

Multi-area response envelope.

Source code in habitipie/models/habits.py
354
355
356
357
class AreaListResponse(HabitipyBaseModel):
    """Multi-area response envelope."""

    data: list[Area]

AreaCreateRequest

Bases: HabitipyRequestModel

Payload for creating a new area.

Source code in habitipie/models/habits.py
360
361
362
363
364
365
class AreaCreateRequest(HabitipyRequestModel):
    """Payload for creating a new area."""

    name: str
    color_hex: str | None = Field(default=None, alias="colorHex")
    icon: str | None = None

AreaUpdateRequest

Bases: HabitipyRequestModel

Payload for updating an existing area.

Source code in habitipie/models/habits.py
368
369
370
371
372
373
class AreaUpdateRequest(HabitipyRequestModel):
    """Payload for updating an existing area."""

    name: str | None = None
    color_hex: str | None = Field(default=None, alias="colorHex")
    icon: str | None = None

TimeOfDay

Bases: HabitipyBaseModel

A time-of-day block (e.g. Morning, Evening).

Source code in habitipie/models/habits.py
376
377
378
379
380
381
382
383
384
class TimeOfDay(HabitipyBaseModel):
    """A time-of-day block (e.g. Morning, Evening)."""

    id: str
    name: str
    icon: str | None = None
    start_time: time = Field(alias="startTime")
    end_time: time = Field(alias="endTime")
    color_hex: str | None = Field(default=None, alias="colorHex")

Habit

Bases: HabitipyBaseModel

A habit resource returned by the Habitify API.

Source code in habitipie/models/habits.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
class Habit(HabitipyBaseModel):
    """A habit resource returned by the Habitify API."""

    id: str
    name: str
    icon: str | None = None
    color_hex: str = Field(alias="colorHex")
    type: HabitType
    description: str | None = None
    occurrence: Occurrence
    start_date: date = Field(alias="startDate")
    created_at: datetime = Field(alias="createdAt")
    is_archived: bool = Field(alias="isArchived")
    log_method: LogMethod = Field(alias="logMethod")
    challenge_id: str | None = Field(default=None, alias="challengeId")
    reminders: Reminders | None = None
    end_condition: EndCondition | None = Field(default=None, alias="endCondition")
    goals: list[Goal]
    custom_unit_name: str | None = Field(default=None, alias="customUnitName")
    areas: list[Area] = Field(default_factory=list)
    time_of_days: list[TimeOfDay] = Field(default_factory=list, alias="timeOfDays")

HabitListPage

Bases: HabitipyBaseModel

Paginated list of habits returned by the API.

Source code in habitipie/models/habits.py
410
411
412
413
414
class HabitListPage(HabitipyBaseModel):
    """Paginated list of habits returned by the API."""

    data: list[Habit]
    pagination: Pagination

HabitJournalStatus

Bases: str, Enum

Completion state of a habit on a given day.

Source code in habitipie/models/habits.py
417
418
419
420
421
422
423
class HabitJournalStatus(str, Enum):
    """Completion state of a habit on a given day."""

    COMPLETED = "completed"
    SKIPPED = "skipped"
    FAILED = "failed"
    IN_PROGRESS = "inprogress"

HabitJournalStreakUnit

Bases: str, Enum

Unit used to measure a streak length.

Source code in habitipie/models/habits.py
426
427
428
429
class HabitJournalStreakUnit(str, Enum):
    """Unit used to measure a streak length."""

    DAY = "day"

HabitJournalCurrentStreak

Bases: HabitipyBaseModel

Current streak metadata for a journal entry.

Source code in habitipie/models/habits.py
432
433
434
435
436
class HabitJournalCurrentStreak(HabitipyBaseModel):
    """Current streak metadata for a journal entry."""

    length: int
    unit: HabitJournalStreakUnit

HabitJournalProgress

Bases: HabitipyBaseModel

Progress toward the habit's goal for the journal day.

Source code in habitipie/models/habits.py
439
440
441
442
443
444
445
class HabitJournalProgress(HabitipyBaseModel):
    """Progress toward the habit's goal for the journal day."""

    current: float
    target: float
    unit: str
    periodicity: GoalPeriodicity

HabitJournalLogInfo

Bases: HabitipyBaseModel

How the journal entry was logged.

Source code in habitipie/models/habits.py
448
449
450
451
class HabitJournalLogInfo(HabitipyBaseModel):
    """How the journal entry was logged."""

    type: LogMethod

HabitJournalEntry

Bases: HabitipyBaseModel

A single habit entry in the daily journal.

Source code in habitipie/models/habits.py
454
455
456
457
458
459
460
461
462
463
464
465
466
class HabitJournalEntry(HabitipyBaseModel):
    """A single habit entry in the daily journal."""

    id: str
    name: str
    status: HabitJournalStatus
    color_hex: str | None = Field(default=None, alias="colorHex")
    icon: str | None = None
    time_of_day_ids: list[str] = Field(default_factory=list, alias="timeOfDayIds")
    type: HabitType
    current_streak: HabitJournalCurrentStreak | None = Field(default=None, alias="currentStreak")
    progress: HabitJournalProgress | None = None
    log_info: HabitJournalLogInfo | None = Field(default=None, alias="logInfo")

HabitJournalPage

Bases: HabitipyBaseModel

Response envelope for the habit journal endpoint.

Source code in habitipie/models/habits.py
469
470
471
472
class HabitJournalPage(HabitipyBaseModel):
    """Response envelope for the habit journal endpoint."""

    data: list[HabitJournalEntry]

HabitStatisticsUnit

Bases: HabitipyBaseModel

Unit information included in habit statistics.

Source code in habitipie/models/habits.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
class HabitStatisticsUnit(HabitipyBaseModel):
    """Unit information included in habit statistics."""

    id: str | None = None
    name: str | None = None
    symbol: UnitSymbol | str

    @field_validator("symbol", mode="before")
    @classmethod
    def coerce_known_symbol(cls, value: object) -> object:
        if isinstance(value, str):
            try:
                return UnitSymbol(value)
            except ValueError:
                return value
        return value

HabitStatisticsDailyProgress

Bases: HabitipyBaseModel

Per-day progress snapshot within habit statistics.

Source code in habitipie/models/habits.py
493
494
495
496
497
498
class HabitStatisticsDailyProgress(HabitipyBaseModel):
    """Per-day progress snapshot within habit statistics."""

    date: date
    total_log: float = Field(alias="totalLog")
    status: HabitJournalStatus

HabitStatistics

Bases: HabitipyBaseModel

Aggregated statistics for a single habit.

Source code in habitipie/models/habits.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
class HabitStatistics(HabitipyBaseModel):
    """Aggregated statistics for a single habit."""

    id: str
    name: str
    type: HabitType
    total_logs: float = Field(alias="totalLogs")
    skips: int
    fails: int
    completions: int
    unit: HabitStatisticsUnit
    periodicity: GoalPeriodicity
    avg: float
    daily_progress: list[HabitStatisticsDailyProgress] = Field(
        default_factory=list, alias="dailyProgress"
    )

HabitStatisticsResponse

Bases: HabitipyBaseModel

Response envelope for the habit statistics endpoint.

Source code in habitipie/models/habits.py
519
520
521
522
class HabitStatisticsResponse(HabitipyBaseModel):
    """Response envelope for the habit statistics endpoint."""

    data: HabitStatistics

HabitResponse

Bases: HabitipyBaseModel

Single-habit response envelope.

Source code in habitipie/models/habits.py
525
526
527
528
class HabitResponse(HabitipyBaseModel):
    """Single-habit response envelope."""

    data: Habit

SuccessMessageResponse

Bases: HabitipyBaseModel

Generic success message returned by mutation endpoints.

Source code in habitipie/models/habits.py
531
532
533
534
class SuccessMessageResponse(HabitipyBaseModel):
    """Generic success message returned by mutation endpoints."""

    message: str

HabitLogRequest

Bases: HabitipyRequestModel

Payload for logging a numeric value against a habit.

Source code in habitipie/models/habits.py
537
538
539
540
541
542
class HabitLogRequest(HabitipyRequestModel):
    """Payload for logging a numeric value against a habit."""

    unit_symbol: UnitSymbol = Field(alias="unitSymbol")
    value: float
    target_date: date | None = Field(default=None, alias="targetDate")

HabitLogResponse

Bases: SuccessMessageResponse

Response from a habit log action.

Source code in habitipie/models/habits.py
545
546
547
548
class HabitLogResponse(SuccessMessageResponse):
    """Response from a habit log action."""

    pass

HabitLogActionRequest

Bases: HabitipyRequestModel

Payload for simple log actions (complete/skip/fail).

Source code in habitipie/models/habits.py
551
552
553
554
class HabitLogActionRequest(HabitipyRequestModel):
    """Payload for simple log actions (complete/skip/fail)."""

    target_date: date | None = Field(default=None, alias="targetDate")

MoodLevel

Bases: str, Enum

Subjective mood scale for a journal note.

Source code in habitipie/models/habits.py
557
558
559
560
561
562
563
564
class MoodLevel(str, Enum):
    """Subjective mood scale for a journal note."""

    VERY_LOW = "veryLow"
    LOW = "low"
    NEUTRAL = "neutral"
    HIGH = "high"
    VERY_HIGH = "veryHigh"

HabitNote

Bases: HabitipyBaseModel

A note attached to a habit log entry.

Source code in habitipie/models/habits.py
567
568
569
570
571
572
573
574
class HabitNote(HabitipyBaseModel):
    """A note attached to a habit log entry."""

    id: str
    content: str | None = None
    mood_level: MoodLevel | None = Field(default=None, alias="moodLevel")
    photos: list[str] | None = None
    created_at: datetime = Field(alias="createdAt")

HabitNoteListResponse

Bases: HabitipyBaseModel

Response envelope for listing habit notes.

Source code in habitipie/models/habits.py
577
578
579
580
class HabitNoteListResponse(HabitipyBaseModel):
    """Response envelope for listing habit notes."""

    data: list[HabitNote]

HabitNoteWriteRequest

Bases: HabitipyRequestModel

Base payload for creating or updating a habit note.

Source code in habitipie/models/habits.py
583
584
585
586
587
588
589
590
591
592
593
594
class HabitNoteWriteRequest(HabitipyRequestModel):
    """Base payload for creating or updating a habit note."""

    content: str | None = None
    mood_level: MoodLevel | None = Field(default=None, alias="moodLevel")
    photos: list[str] | None = None

    @model_validator(mode="after")
    def require_at_least_one_field(self) -> HabitNoteWriteRequest:
        if not self.model_fields_set:
            raise ValueError("At least one note field must be provided.")
        return self

HabitNoteCreateRequest

Bases: HabitNoteWriteRequest

Payload for creating a new habit note.

Source code in habitipie/models/habits.py
597
598
599
600
class HabitNoteCreateRequest(HabitNoteWriteRequest):
    """Payload for creating a new habit note."""

    pass

HabitNoteUpdateRequest

Bases: HabitNoteWriteRequest

Payload for updating an existing habit note.

Uses exclude_unset=True so that None can be sent explicitly to clear a field.

Source code in habitipie/models/habits.py
603
604
605
606
607
608
609
610
611
612
613
614
class HabitNoteUpdateRequest(HabitNoteWriteRequest):
    """Payload for updating an existing habit note.

    Uses ``exclude_unset=True`` so that ``None`` can be sent explicitly to
    clear a field.
    """

    def to_request_body(self) -> dict[str, object]:
        return cast(
            dict[str, object],
            self.model_dump(by_alias=True, exclude_unset=True, mode="json"),
        )

HabitCreateRequest

Bases: HabitipyRequestModel

Payload for creating a new habit.

Source code in habitipie/models/habits.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
class HabitCreateRequest(HabitipyRequestModel):
    """Payload for creating a new habit."""

    name: str
    type: HabitType
    description: str | None = None
    occurrence: HabitCreateOccurrence | None = None
    start_date: date | None = Field(default=None, alias="startDate")
    icon: str | None = None
    color_hex: str | None = Field(default=None, alias="colorHex")
    custom_unit_name: str | None = Field(default=None, alias="customUnitName")
    area_ids: list[str] | None = Field(default=None, alias="areaIds")
    time_of_day_ids: list[str] | None = Field(default=None, alias="timeOfDayIds")
    goal: HabitCreateGoal | None = None
    reminders: HabitCreateReminders | None = None
    end_condition: HabitCreateEndCondition | None = Field(default=None, alias="endCondition")

HabitUpdateRequest

Bases: HabitipyRequestModel

Payload for updating an existing habit.

Empty nested objects (e.g. {"goal": {}}) are pruned so the server does not receive ambiguous partial updates.

Source code in habitipie/models/habits.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
class HabitUpdateRequest(HabitipyRequestModel):
    """Payload for updating an existing habit.

    Empty nested objects (e.g. ``{"goal": {}}``) are pruned so the server
    does not receive ambiguous partial updates.
    """

    name: str | None = None
    description: str | None = None
    occurrence: HabitCreateOccurrence | None = None
    start_date: date | None = Field(default=None, alias="startDate")
    icon: str | None = None
    color_hex: str | None = Field(default=None, alias="colorHex")
    custom_unit_name: str | None = Field(default=None, alias="customUnitName")
    area_ids: list[str] | None = Field(default=None, alias="areaIds")
    time_of_day_ids: list[str] | None = Field(default=None, alias="timeOfDayIds")
    goal: HabitCreateGoal | None = None
    reminders: HabitUpdateReminders | None = None
    end_condition: HabitCreateEndCondition | None = Field(default=None, alias="endCondition")

    def to_request_body(self) -> dict[str, object]:
        payload = self.model_dump(by_alias=True, exclude_none=True, mode="json")
        return cast(dict[str, object], _prune_empty_dicts(payload) or {})

Pagination

Bases: BaseModel

Pagination metadata returned by list endpoints.

Attributes:

Name Type Description
total int

Total number of items available across all pages.

limit int

Maximum number of items returned in the current page.

offset int

Number of items skipped before the current page.

Source code in habitipie/pagination.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Pagination(BaseModel):
    """Pagination metadata returned by list endpoints.

    Attributes:
        total: Total number of items available across all pages.
        limit: Maximum number of items returned in the current page.
        offset: Number of items skipped before the current page.
    """

    model_config = ConfigDict(extra="ignore")

    total: int
    limit: int = Field(..., ge=1)
    offset: int = Field(..., ge=0)

Errors

ResponseDecodeError

Bases: DecodingError

Raised when a response body cannot be decoded as JSON.

Source code in habitipie/errors.py
8
9
class ResponseDecodeError(httpx.DecodingError):
    """Raised when a response body cannot be decoded as JSON."""

UnexpectedResponseShapeError

Bases: ResponseDecodeError

Raised when a response JSON payload does not match the expected top-level shape.

Source code in habitipie/errors.py
12
13
class UnexpectedResponseShapeError(ResponseDecodeError):
    """Raised when a response JSON payload does not match the expected top-level shape."""

ApiError

Bases: HTTPStatusError

Base exception for Habitify API error responses.

Attributes:

Name Type Description
payload

The decoded response body, if available. May be a dict, str, or None when the body could not be parsed.

Source code in habitipie/errors.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class ApiError(httpx.HTTPStatusError):
    """Base exception for Habitify API error responses.

    Attributes:
        payload: The decoded response body, if available. May be a dict, str,
            or ``None`` when the body could not be parsed.
    """

    def __init__(
        self,
        message: str,
        *,
        request: httpx.Request,
        response: httpx.Response,
        payload: Any | None = None,
    ) -> None:
        super().__init__(message, request=request, response=response)
        self.payload = payload

AuthenticationError

Bases: ApiError

Raised when authentication is missing or invalid (HTTP 401).

Source code in habitipie/errors.py
36
37
class AuthenticationError(ApiError):
    """Raised when authentication is missing or invalid (HTTP 401)."""

NotFoundError

Bases: ApiError

Raised when the requested resource is missing (HTTP 404).

Source code in habitipie/errors.py
40
41
class NotFoundError(ApiError):
    """Raised when the requested resource is missing (HTTP 404)."""

RateLimitError

Bases: ApiError

Raised when the Habitify API rate limit is exceeded (HTTP 429).

Source code in habitipie/errors.py
44
45
class RateLimitError(ApiError):
    """Raised when the Habitify API rate limit is exceeded (HTTP 429)."""

ServerError

Bases: ApiError

Raised when the Habitify API returns a server-side error (HTTP 5xx).

Source code in habitipie/errors.py
48
49
class ServerError(ApiError):
    """Raised when the Habitify API returns a server-side error (HTTP 5xx)."""

raise_for_api_status(response: httpx.Response) -> None

Raise a Habitify-specific exception for non-2xx responses.

Maps common HTTP status codes to typed subclasses:

  • 401 → :class:AuthenticationError
  • 404 → :class:NotFoundError
  • 429 → :class:RateLimitError
  • 5xx → :class:ServerError
  • others → :class:ApiError

The response body is parsed as JSON when possible and attached to the exception via .payload.

Parameters:

Name Type Description Default
response Response

The HTTP response to inspect.

required

Raises:

Type Description
ApiError

If the response status is not successful.

Source code in habitipie/errors.py
 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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def raise_for_api_status(response: httpx.Response) -> None:
    """Raise a Habitify-specific exception for non-2xx responses.

    Maps common HTTP status codes to typed subclasses:

    * 401 → :class:`AuthenticationError`
    * 404 → :class:`NotFoundError`
    * 429 → :class:`RateLimitError`
    * 5xx → :class:`ServerError`
    * others → :class:`ApiError`

    The response body is parsed as JSON when possible and attached to the
    exception via ``.payload``.

    Args:
        response: The HTTP response to inspect.

    Raises:
        ApiError: If the response status is not successful.
    """
    payload: Any | None = None
    message = response.reason_phrase
    cause: httpx.HTTPStatusError | None = None

    try:
        response.raise_for_status()
        return
    except httpx.HTTPStatusError as exc:
        cause = exc
        request = exc.request
        response = exc.response

    try:
        payload = response.json()
    except ValueError:
        payload = response.text or None

    if isinstance(payload, dict):
        payload_message = payload.get("message") or payload.get("error")
        if isinstance(payload_message, str) and payload_message:
            message = payload_message
    elif isinstance(payload, str) and payload:
        message = payload

    error_cls: type[ApiError]
    if response.status_code == 400:
        error_cls = ApiError
    elif response.status_code == 401:
        error_cls = AuthenticationError
    elif response.status_code == 404:
        error_cls = NotFoundError
    elif response.status_code == 429:
        error_cls = RateLimitError
    elif response.status_code >= 500:
        error_cls = ServerError
    else:
        error_cls = ApiError

    raise error_cls(message, request=request, response=response, payload=payload) from cause