Skip to content

Trackers

toggl_api.TrackerBody dataclass

Bases: BaseBody

JSON body dataclass for PUT, POST & PATCH requests.

Examples:

>>> TrackerBody(description="What a wonderful tracker description!", project_id=2123132)
TrackerBody(description="What a wonderful tracker description!", project_id=2123132)

format(endpoint: str, **body: Any) -> dict[str, Any]

Formats the body for JSON requests.

Gets called by the endpoint methods before requesting.

Parameters:

  • endpoint (str) –

    The endpoints name for filtering purposes.

  • body (Any, default: {} ) –

    Additional body arguments that the endpoint requires.

Returns:

  • dict ( dict[str, Any] ) –

    JSON compatible formatted body.

toggl_api.TrackerEndpoint

Bases: TogglCachedEndpoint[TogglTracker]

Endpoint for modifying and creating trackers.

See the UserEndpoint for GET specific requests.

Official Documentation

Examples:

>>> tracker_endpoint = TrackerEndpoint(324525, BasicAuth(...), JSONCache(Path("cache")))
>>> body = TrackerBody(description="What a wonderful tracker description!", project_id=2123132)
>>> tracker = tracker_endpoint.add(body)
TogglTracker(id=58687689, name="What a wonderful tracker description!", project=2123132, ...)
>>> tracker_endpoint.delete(tracker)
None

Parameters:

  • workspace_id (int | TogglWorkspace) –

    The workspace the Toggl trackers belong to.

  • auth (BasicAuth) –

    Authentication for the client.

  • cache (TogglCache[TogglTracker]) –

    Where to cache trackers.

  • timeout (int, default: 10 ) –

    How long it takes for the client to timeout. Keyword Only. Defaults to 10 seconds.

  • re_raise (bool, default: False ) –

    Whether to raise all HTTPStatusError errors and not handle them internally. Keyword Only.

  • retries (int, default: 3 ) –

    Max retries to attempt if the server returns a 5xx status_code. Has no effect if re_raise is True. Keyword Only.

Source code in toggl_api/tracker.py
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
class TrackerEndpoint(TogglCachedEndpoint[TogglTracker]):
    """Endpoint for modifying and creating trackers.

    See the [UserEndpoint][toggl_api.UserEndpoint] for _GET_ specific requests.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries)

    Examples:
        >>> tracker_endpoint = TrackerEndpoint(324525, BasicAuth(...), JSONCache(Path("cache")))

        >>> body = TrackerBody(description="What a wonderful tracker description!", project_id=2123132)
        >>> tracker = tracker_endpoint.add(body)
        TogglTracker(id=58687689, name="What a wonderful tracker description!", project=2123132, ...)

        >>> tracker_endpoint.delete(tracker)
        None

    Params:
        workspace_id: The workspace the Toggl trackers belong to.
        auth: Authentication for the client.
        cache: Where to cache trackers.
        timeout: How long it takes for the client to timeout. Keyword Only.
            Defaults to 10 seconds.
        re_raise: Whether to raise all HTTPStatusError errors and not handle them
            internally. Keyword Only.
        retries: Max retries to attempt if the server returns a *5xx* status_code.
            Has no effect if re_raise is `True`. Keyword Only.
    """

    TRACKER_ALREADY_STOPPED: Final[int] = 409

    def __init__(
        self,
        workspace_id: int | TogglWorkspace,
        auth: BasicAuth,
        cache: TogglCache[TogglTracker],
        *,
        timeout: int = 10,
        re_raise: bool = False,
        retries: int = 3,
    ) -> None:
        super().__init__(0, auth, cache, timeout=timeout, re_raise=re_raise, retries=retries)
        self.workspace_id = workspace_id if isinstance(workspace_id, int) else workspace_id.id

    def edit(
        self,
        tracker: TogglTracker | int,
        body: TrackerBody,
        *,
        meta: bool = False,
    ) -> TogglTracker:
        """Edit an existing tracker based on the supplied parameters within the body.

        This endpoint always hit the external API in order to keep trackers consistent.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#put-timeentries)

        Examples:
            >>> body = TrackerBody(description="What a wonderful tracker description!", project_id=2123132)
            >>> tracker_endpoint.edit(58687684, body)
            TogglTracker(id=58687684, name="What a wonderful tracker description!", project=2123132, ...)

        Args:
            tracker: Target tracker model or id to edit.
            body: Updated content to add.
            meta: Should the response contain data for meta entities.

        Raises:
            HTTPStatusError: For anything thats not a *ok* status code.

        Returns:
            A new model if successful else None.
        """
        if (body.tag_ids or body.tags) and not body.tag_action:
            body.tag_action = "add"

        if isinstance(tracker, TogglTracker):
            tracker = tracker.id

        return self.request(
            f"/{tracker}",
            method=RequestMethod.PUT,
            body=body.format("edit", workspace_id=self.workspace_id, meta=meta),
            refresh=True,
        )

    def _bulk_edit(
        self,
        trackers: list[int],
        body: list[BulkEditParameter],
    ) -> dict[str, list[int]]:
        url = "/" + ",".join([str(t) for t in trackers])

        return self.request(
            url,
            body=body,
            refresh=True,
            method=RequestMethod.PATCH,
            raw=True,
        ).json()

    def bulk_edit(
        self,
        *trackers: int | TogglTracker,
        body: TrackerBody,
    ) -> Edits:
        """Bulk edit multiple trackers at the same time.

        Patch will be executed partially when there are errors with some records.
        No transaction, no rollback.

        There is a limit of editing 100 trackers at the same time, so the
        method will make multiple calls if the count exceeds that limit.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries/#patch-bulk-editing-time-entries)

        Examples:
            >>> body = TrackerBody(description="All these trackers belong to me!")
            >>> tracker_endpoint.bulk_edit(1235151, 214124, body)
            Edits(successes=[1235151, 214124], failures=[])

        Args:
            trackers: All trackers that need to be edited.
            body: The parameters that need to be edited.

        Raises:
            HTTPStatusError: For anything thats not a *ok* status code.

        Returns:
            Successeful or failed ids editing the trackers.
        """
        tracker_ids = [t if isinstance(t, int) else t.id for t in trackers]
        requests = math.ceil(len(tracker_ids) / 100)
        success: list[int]
        failure: list[int]
        success, failure = [], []

        fmt_body = body._format_bulk_edit()  # noqa: SLF001
        for i in range(requests):
            edit = self._bulk_edit(tracker_ids[100 * i : 100 + (100 * i)], fmt_body)
            success.extend(edit["success"])
            failure.extend(edit["failure"])

        return Edits(success, failure)

    def delete(self, tracker: TogglTracker | int) -> None:
        """Delete a tracker from Toggl.

        This endpoint always hit the external API in order to keep trackers consistent.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#delete-timeentries)

        Examples:
            >>> tracker_endpoint.delete(58687684)
            None

        Args:
            tracker: Tracker object with ID to delete.

        Raises:
            HTTPStatusError: If anything thats not a '404' or 'ok' code is returned.

        Returns:
            If the tracker was deleted or not found at all.
        """
        tracker_id = tracker if isinstance(tracker, int) else tracker.id
        try:
            self.request(f"/{tracker_id}", method=RequestMethod.DELETE, refresh=True)
        except HTTPStatusError as err:
            if self.re_raise or err.response.status_code != codes.NOT_FOUND:
                raise
            log.warning(
                "Tracker with id %s was either already deleted or did not exist in the first place!",
                tracker_id,
            )

        if isinstance(tracker, int):
            trk = self.cache.find_entry({"id": tracker})
            if not isinstance(trk, TogglTracker):
                return
            tracker = trk

        self.cache.delete_entries(tracker)
        self.cache.commit()

    def stop(self, tracker: TogglTracker | int) -> TogglTracker | None:
        """Stops a running tracker.

        This endpoint always hit the external API in order to keep trackers consistent.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#patch-stop-timeentry)

        Examples:
            >>> tracker_endpoint.stop(58687684)
            TogglTracker(id=58687684, name="What a wonderful tracker description!", ...)

        Args:
            tracker: Tracker id to stop. An integer or model.

        Raises:
            HTTPStatusError: For anything thats not 'ok' or a '409' status code.

        Returns:
           If the tracker was stopped or if the tracker wasn't running it will return None.
        """
        if isinstance(tracker, TogglTracker):
            tracker = tracker.id
        try:
            return self.request(
                f"/{tracker}/stop",
                method=RequestMethod.PATCH,
                refresh=True,
            )
        except HTTPStatusError as err:
            if self.re_raise or err.response.status_code != self.TRACKER_ALREADY_STOPPED:
                raise
            log.warning("Tracker with id %s was already stopped!", tracker)
        return None

    def add(self, body: TrackerBody) -> TogglTracker:
        """Add a new tracker.

        This endpoint always hit the external API in order to keep trackers consistent.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#post-timeentries)

        Examples:
            >>> body = TrackerBody(description="Tracker description!", project_id=2123132)
            >>> tracker_endpoint.edit(body)
            TogglTracker(id=78895400, name="Tracker description!", project=2123132, ...)

        Args:
            body: Body of the request. Description must be set. If start date
                is not set it will be set to current time with duration set
                to -1 for a running tracker.

        Raises:
            HTTPStatusError: For anything that wasn't an *ok* status code.
            NamingError: Description must be set in order to create a new tracker.

        Returns:
            The tracker that was created.
        """
        if not isinstance(body.description, str):
            warnings.warn(
                "DEPRECATED: 'TypeError' is being swapped for a 'NamingError'.",
                DeprecationWarning,
                stacklevel=2,
            )
            msg = "Description must be set in order to create a tracker!"
            raise TypeError(msg)
        if not body.description:
            msg = "Description must be set in order to create a tracker!"
            raise NamingError(msg)

        if body.start is None and body.start_date is None:
            body.start = datetime.now(tz=timezone.utc)
            log.info(
                "Body is missing a start. Setting to %s...",
                body.start,
                extra={"body": body},
            )
            if body.stop is None:
                body.duration = -1

        body.tag_action = "add"

        return self.request(
            "",
            method=RequestMethod.POST,
            body=body.format("add", workspace_id=self.workspace_id),
            refresh=True,
        )

    @property
    def endpoint(self) -> str:
        return f"workspaces/{self.workspace_id}/time_entries"

    @property
    def model(self) -> type[TogglTracker]:
        return TogglTracker

edit(tracker: TogglTracker | int, body: TrackerBody, *, meta: bool = False) -> TogglTracker

Edit an existing tracker based on the supplied parameters within the body.

This endpoint always hit the external API in order to keep trackers consistent.

Official Documentation

Examples:

>>> body = TrackerBody(description="What a wonderful tracker description!", project_id=2123132)
>>> tracker_endpoint.edit(58687684, body)
TogglTracker(id=58687684, name="What a wonderful tracker description!", project=2123132, ...)

Parameters:

  • tracker (TogglTracker | int) –

    Target tracker model or id to edit.

  • body (TrackerBody) –

    Updated content to add.

  • meta (bool, default: False ) –

    Should the response contain data for meta entities.

Raises:

  • HTTPStatusError

    For anything thats not a ok status code.

Returns:

Source code in toggl_api/tracker.py
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
def edit(
    self,
    tracker: TogglTracker | int,
    body: TrackerBody,
    *,
    meta: bool = False,
) -> TogglTracker:
    """Edit an existing tracker based on the supplied parameters within the body.

    This endpoint always hit the external API in order to keep trackers consistent.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#put-timeentries)

    Examples:
        >>> body = TrackerBody(description="What a wonderful tracker description!", project_id=2123132)
        >>> tracker_endpoint.edit(58687684, body)
        TogglTracker(id=58687684, name="What a wonderful tracker description!", project=2123132, ...)

    Args:
        tracker: Target tracker model or id to edit.
        body: Updated content to add.
        meta: Should the response contain data for meta entities.

    Raises:
        HTTPStatusError: For anything thats not a *ok* status code.

    Returns:
        A new model if successful else None.
    """
    if (body.tag_ids or body.tags) and not body.tag_action:
        body.tag_action = "add"

    if isinstance(tracker, TogglTracker):
        tracker = tracker.id

    return self.request(
        f"/{tracker}",
        method=RequestMethod.PUT,
        body=body.format("edit", workspace_id=self.workspace_id, meta=meta),
        refresh=True,
    )

bulk_edit(*trackers: int | TogglTracker, body: TrackerBody) -> Edits

Bulk edit multiple trackers at the same time.

Patch will be executed partially when there are errors with some records. No transaction, no rollback.

There is a limit of editing 100 trackers at the same time, so the method will make multiple calls if the count exceeds that limit.

Official Documentation

Examples:

>>> body = TrackerBody(description="All these trackers belong to me!")
>>> tracker_endpoint.bulk_edit(1235151, 214124, body)
Edits(successes=[1235151, 214124], failures=[])

Parameters:

  • trackers (int | TogglTracker, default: () ) –

    All trackers that need to be edited.

  • body (TrackerBody) –

    The parameters that need to be edited.

Raises:

  • HTTPStatusError

    For anything thats not a ok status code.

Returns:

  • Edits

    Successeful or failed ids editing the trackers.

Source code in toggl_api/tracker.py
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
def bulk_edit(
    self,
    *trackers: int | TogglTracker,
    body: TrackerBody,
) -> Edits:
    """Bulk edit multiple trackers at the same time.

    Patch will be executed partially when there are errors with some records.
    No transaction, no rollback.

    There is a limit of editing 100 trackers at the same time, so the
    method will make multiple calls if the count exceeds that limit.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries/#patch-bulk-editing-time-entries)

    Examples:
        >>> body = TrackerBody(description="All these trackers belong to me!")
        >>> tracker_endpoint.bulk_edit(1235151, 214124, body)
        Edits(successes=[1235151, 214124], failures=[])

    Args:
        trackers: All trackers that need to be edited.
        body: The parameters that need to be edited.

    Raises:
        HTTPStatusError: For anything thats not a *ok* status code.

    Returns:
        Successeful or failed ids editing the trackers.
    """
    tracker_ids = [t if isinstance(t, int) else t.id for t in trackers]
    requests = math.ceil(len(tracker_ids) / 100)
    success: list[int]
    failure: list[int]
    success, failure = [], []

    fmt_body = body._format_bulk_edit()  # noqa: SLF001
    for i in range(requests):
        edit = self._bulk_edit(tracker_ids[100 * i : 100 + (100 * i)], fmt_body)
        success.extend(edit["success"])
        failure.extend(edit["failure"])

    return Edits(success, failure)

delete(tracker: TogglTracker | int) -> None

Delete a tracker from Toggl.

This endpoint always hit the external API in order to keep trackers consistent.

Official Documentation

Examples:

>>> tracker_endpoint.delete(58687684)
None

Parameters:

  • tracker (TogglTracker | int) –

    Tracker object with ID to delete.

Raises:

  • HTTPStatusError

    If anything thats not a '404' or 'ok' code is returned.

Returns:

  • None

    If the tracker was deleted or not found at all.

Source code in toggl_api/tracker.py
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
def delete(self, tracker: TogglTracker | int) -> None:
    """Delete a tracker from Toggl.

    This endpoint always hit the external API in order to keep trackers consistent.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#delete-timeentries)

    Examples:
        >>> tracker_endpoint.delete(58687684)
        None

    Args:
        tracker: Tracker object with ID to delete.

    Raises:
        HTTPStatusError: If anything thats not a '404' or 'ok' code is returned.

    Returns:
        If the tracker was deleted or not found at all.
    """
    tracker_id = tracker if isinstance(tracker, int) else tracker.id
    try:
        self.request(f"/{tracker_id}", method=RequestMethod.DELETE, refresh=True)
    except HTTPStatusError as err:
        if self.re_raise or err.response.status_code != codes.NOT_FOUND:
            raise
        log.warning(
            "Tracker with id %s was either already deleted or did not exist in the first place!",
            tracker_id,
        )

    if isinstance(tracker, int):
        trk = self.cache.find_entry({"id": tracker})
        if not isinstance(trk, TogglTracker):
            return
        tracker = trk

    self.cache.delete_entries(tracker)
    self.cache.commit()

stop(tracker: TogglTracker | int) -> TogglTracker | None

Stops a running tracker.

This endpoint always hit the external API in order to keep trackers consistent.

Official Documentation

Examples:

>>> tracker_endpoint.stop(58687684)
TogglTracker(id=58687684, name="What a wonderful tracker description!", ...)

Parameters:

  • tracker (TogglTracker | int) –

    Tracker id to stop. An integer or model.

Raises:

  • HTTPStatusError

    For anything thats not 'ok' or a '409' status code.

Returns:

  • TogglTracker | None

    If the tracker was stopped or if the tracker wasn't running it will return None.

Source code in toggl_api/tracker.py
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
def stop(self, tracker: TogglTracker | int) -> TogglTracker | None:
    """Stops a running tracker.

    This endpoint always hit the external API in order to keep trackers consistent.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#patch-stop-timeentry)

    Examples:
        >>> tracker_endpoint.stop(58687684)
        TogglTracker(id=58687684, name="What a wonderful tracker description!", ...)

    Args:
        tracker: Tracker id to stop. An integer or model.

    Raises:
        HTTPStatusError: For anything thats not 'ok' or a '409' status code.

    Returns:
       If the tracker was stopped or if the tracker wasn't running it will return None.
    """
    if isinstance(tracker, TogglTracker):
        tracker = tracker.id
    try:
        return self.request(
            f"/{tracker}/stop",
            method=RequestMethod.PATCH,
            refresh=True,
        )
    except HTTPStatusError as err:
        if self.re_raise or err.response.status_code != self.TRACKER_ALREADY_STOPPED:
            raise
        log.warning("Tracker with id %s was already stopped!", tracker)
    return None

add(body: TrackerBody) -> TogglTracker

Add a new tracker.

This endpoint always hit the external API in order to keep trackers consistent.

Official Documentation

Examples:

>>> body = TrackerBody(description="Tracker description!", project_id=2123132)
>>> tracker_endpoint.edit(body)
TogglTracker(id=78895400, name="Tracker description!", project=2123132, ...)

Parameters:

  • body (TrackerBody) –

    Body of the request. Description must be set. If start date is not set it will be set to current time with duration set to -1 for a running tracker.

Raises:

  • HTTPStatusError

    For anything that wasn't an ok status code.

  • NamingError

    Description must be set in order to create a new tracker.

Returns:

Source code in toggl_api/tracker.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def add(self, body: TrackerBody) -> TogglTracker:
    """Add a new tracker.

    This endpoint always hit the external API in order to keep trackers consistent.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#post-timeentries)

    Examples:
        >>> body = TrackerBody(description="Tracker description!", project_id=2123132)
        >>> tracker_endpoint.edit(body)
        TogglTracker(id=78895400, name="Tracker description!", project=2123132, ...)

    Args:
        body: Body of the request. Description must be set. If start date
            is not set it will be set to current time with duration set
            to -1 for a running tracker.

    Raises:
        HTTPStatusError: For anything that wasn't an *ok* status code.
        NamingError: Description must be set in order to create a new tracker.

    Returns:
        The tracker that was created.
    """
    if not isinstance(body.description, str):
        warnings.warn(
            "DEPRECATED: 'TypeError' is being swapped for a 'NamingError'.",
            DeprecationWarning,
            stacklevel=2,
        )
        msg = "Description must be set in order to create a tracker!"
        raise TypeError(msg)
    if not body.description:
        msg = "Description must be set in order to create a tracker!"
        raise NamingError(msg)

    if body.start is None and body.start_date is None:
        body.start = datetime.now(tz=timezone.utc)
        log.info(
            "Body is missing a start. Setting to %s...",
            body.start,
            extra={"body": body},
        )
        if body.stop is None:
            body.duration = -1

    body.tag_action = "add"

    return self.request(
        "",
        method=RequestMethod.POST,
        body=body.format("add", workspace_id=self.workspace_id),
        refresh=True,
    )

toggl_api.UserEndpoint

Bases: TogglCachedEndpoint[TogglTracker]

Endpoint for retrieving and fetching trackers with GET requests.

See the TrackerEndpoint for modifying trackers.

Official Documentation

Parameters:

  • workspace_id (int | TogglWorkspace) –

    The workspace the Toggl trackers belong to.

  • auth (BasicAuth) –

    Authentication for the client.

  • cache (TogglCache[TogglTracker]) –

    Cache object where trackers are stored.

  • timeout (int, default: 10 ) –

    How long it takes for the client to timeout. Keyword Only. Defaults to 10 seconds.

  • re_raise (bool, default: False ) –

    Whether to raise all HTTPStatusError errors and not handle them internally. Keyword Only.

  • retries (int, default: 3 ) –

    Max retries to attempt if the server returns a 5xx status_code. Has no effect if re_raise is True. Keyword Only.

Source code in toggl_api/user.py
 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
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
class UserEndpoint(TogglCachedEndpoint[TogglTracker]):
    """Endpoint for retrieving and fetching trackers with GET requests.

    See the [TrackerEndpoint][toggl_api.TrackerEndpoint] for modifying trackers.

    [Official Documentation](https://engineering.toggl.com/docs/api/me)

    Params:
        workspace_id: The workspace the Toggl trackers belong to.
        auth: Authentication for the client.
        cache: Cache object where trackers are stored.
        timeout: How long it takes for the client to timeout. Keyword Only.
            Defaults to 10 seconds.
        re_raise: Whether to raise all HTTPStatusError errors and not handle them
            internally. Keyword Only.
        retries: Max retries to attempt if the server returns a *5xx* status_code.
            Has no effect if re_raise is `True`. Keyword Only.
    """

    TRACKER_NOT_RUNNING: Final[int] = codes.METHOD_NOT_ALLOWED

    def __init__(
        self,
        workspace_id: int | TogglWorkspace,
        auth: BasicAuth,
        cache: TogglCache[TogglTracker],
        *,
        timeout: int = 10,
        re_raise: bool = False,
        retries: int = 3,
    ) -> None:
        super().__init__(0, auth, cache, timeout=timeout, re_raise=re_raise, retries=retries)
        self.workspace_id = workspace_id if isinstance(workspace_id, int) else workspace_id.id

    def _current_refresh(self, tracker: TogglTracker | None) -> None:
        if tracker is None:
            for t in self.cache.query(TogglQuery("stop", None)):
                try:
                    self.get(t, refresh=True)
                except HTTPStatusError:
                    log.exception("%s")
                    return

    def current(self, *, refresh: bool = True) -> TogglTracker | None:
        """Get current running tracker. Returns None if no tracker is running.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#get-get-current-time-entry)

        Examples:
            >>> user_endpoint.current()
            None

            >>> user_endpoint.current(refresh=True)
            TogglTracker(...)

        Args:
            refresh: Whether to check the remote API for running trackers.
                If 'refresh' is True it will check if there are any other running
                trackers and update if the 'stop' attribute is None.

        Raises:
            HTTPStatusError: If the request is not a success or any error that's
                not a '405' status code.

        Returns:
            A model from cache or the API. None if nothing is running.
        """

        if not refresh:
            query = list(self.cache.query(TogglQuery("stop", None)))
            return query[0] if query else None

        try:
            response = self.request("/time_entries/current", refresh=refresh)
        except HTTPStatusError as err:
            if not self.re_raise and err.response.status_code == self.TRACKER_NOT_RUNNING:
                log.warning("No tracker is currently running!")
                response = None
            else:
                raise

        self._current_refresh(response)

        return response if isinstance(response, TogglTracker) else None

    def _collect_cache(
        self,
        since: Optional[int | datetime] = None,
        before: Optional[date] = None,
        start_date: Optional[date] = None,
        end_date: Optional[date] = None,
    ) -> list[TogglTracker]:
        cache: list[TogglTracker] = []
        if since or before:
            queries: list[TogglQuery[date]] = []

            if since:
                since = datetime.fromtimestamp(since, tz=timezone.utc) if isinstance(since, int) else since
                queries.append(TogglQuery("timestamp", since, Comparison.GREATER_THEN))

            if before:
                queries.append(TogglQuery("start", before, Comparison.LESS_THEN))

            cache.extend(self.query(*queries))

        elif start_date and end_date:
            cache.extend(
                self.query(
                    TogglQuery("start", start_date, Comparison.GREATER_THEN_OR_EQUAL),
                    TogglQuery("start", end_date, Comparison.LESS_THEN_OR_EQUAL),
                ),
            )
        else:
            cache.extend(self.load_cache())

        return cache

    def collect(
        self,
        since: Optional[int | datetime] = None,
        before: Optional[date] = None,
        start_date: Optional[date] = None,
        end_date: Optional[date] = None,
        *,
        refresh: bool = False,
    ) -> list[TogglTracker]:
        """Get a set of trackers depending on specified parameters.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#get-timeentries)

        Missing meta and include_sharing query flags not supported by wrapper at
        the moment.

        Examples:
            >>> collect(since=17300032362, before=date(2024, 11, 27))

            >>> collect(refresh=True)

            >>> collect(start_date=date(2024, 11, 27), end_date=date(2024, 12, 27))

        Args:
            since: Get entries modified since this date using UNIX timestamp.
                Includes deleted ones if refreshing.
            before: Get entries with start time, before given date (YYYY-MM-DD)
                or with time in RFC3339 format.
            start_date: Get entries with start time, from start_date YYYY-MM-DD
                or with time in RFC3339 format. To be used with end_date.
            end_date: Get entries with start time, until end_date YYYY-MM-DD or
                with time in RFC3339 format. To be used with start_date.
            refresh: Whether to refresh the cache or not.

        Raises:
            DateTimeError: If the dates are not in the correct ranges.
            HTTPStatusError: If the request is not a successful status code.

        Returns:
           List of TogglTracker objects that are within specified parameters.
                Empty if none is matched.
        """

        if start_date and end_date:
            if end_date < start_date:
                msg = "end_date must be after the start_date!"
                raise DateTimeError(msg)
            if start_date > datetime.now(tz=timezone.utc):
                msg = "start_date must not be earlier than the current date!"
                raise DateTimeError(msg)

        if not refresh:
            return self._collect_cache(since, before, start_date, end_date)

        params = "/time_entries"
        if since or before:
            if since:
                params += f"?since={get_timestamp(since)}"

            if before:
                params += "&" if since else "?"
                params += f"before={format_iso(before)}"

        elif start_date and end_date:
            params += f"?start_date={format_iso(start_date)}&end_date={format_iso(end_date)}"

        response = self.request(params, refresh=refresh)

        return response if isinstance(response, list) else []

    def get(
        self,
        tracker_id: int | TogglTracker,
        *,
        refresh: bool = False,
    ) -> TogglTracker | None:
        """Get a single tracker by ID.

        [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#get-get-a-time-entry-by-id)

        Args:
            tracker_id: ID of the tracker to get.
            refresh: Whether to refresh the cache or not.

        Raises:
            HTTPStatusError: If anything thats not a *ok* or *404* status code
                is returned.

        Returns:
            TogglTracker object or None if not found.
        """
        if isinstance(tracker_id, TogglTracker):
            tracker_id = tracker_id.id

        if not refresh:
            return self.cache.find_entry({"id": tracker_id})

        try:
            response = self.request(
                f"/time_entries/{tracker_id}",
                refresh=refresh,
            )
        except HTTPStatusError as err:
            if not self.re_raise and err.response.status_code == codes.NOT_FOUND:
                log.warning("Tracker with id %s does not exist!", tracker_id)
                return None
            raise

        return response

    def check_authentication(self) -> bool:
        """Check if user is correctly authenticated with the Toggl API.

        [Official Documentation](https://engineering.toggl.com/docs/api/me#get-logged)
        """
        warnings.warn(
            (
                "DEPRECATED: 'check_authentication' is being removed. "
                "Use the static method 'verify_authentication instead!"
            ),
            stacklevel=3,
        )
        try:
            TogglEndpoint.request(self, "/logged")
        except HTTPStatusError as err:
            log.critical("Failed to verify authentication!")
            log.exception("%s")
            if err.response.status_code != codes.FORBIDDEN:
                raise

            return False

        return True

    @staticmethod
    def verify_authentication(auth: BasicAuth) -> bool:
        """Check if user is correctly authenticated with the Toggl API.

        [Official Documentation](https://engineering.toggl.com/docs/api/me#get-logged)

        Examples:
            >>> UserEndpoint.verify_authentication(auth)
            True

            >>> auth = generate_authentication()
            >>> UserEndpoint.verify_authentication(auth)
            True

        Args:
            auth: Basic authentication object either created manually or one
                of the provided authentication utilities.

        Raises:
            HTTPStatusError: If anything that is an error that is not a FORBIDDEN code.

        Returns:
            True if successfully verified authentication else False.
        """
        try:
            httpx.get(TogglEndpoint.BASE_ENDPOINT + "me/logged", auth=auth).raise_for_status()
        except HTTPStatusError as err:
            log.critical("Failed to verify authentication!")
            log.exception("%s")
            if err.response.status_code != codes.FORBIDDEN:
                raise

            return False

        return True

    def get_details(self) -> dict[str, Any]:
        """Returns details for the current user.

        [Official Documentation](https://engineering.toggl.com/docs/api/me#get-me)

        Raises:
            HTTPStatusError: If the request is not a successful status code.

        Returns:
            User details in a raw dictionary.
        """
        return TogglEndpoint.request(self, "", raw=True).json()

    @property
    def endpoint(self) -> str:
        return "me"

    @property
    def model(self) -> type[TogglTracker]:
        return TogglTracker

current(*, refresh: bool = True) -> TogglTracker | None

Get current running tracker. Returns None if no tracker is running.

Official Documentation

Examples:

>>> user_endpoint.current()
None
>>> user_endpoint.current(refresh=True)
TogglTracker(...)

Parameters:

  • refresh (bool, default: True ) –

    Whether to check the remote API for running trackers. If 'refresh' is True it will check if there are any other running trackers and update if the 'stop' attribute is None.

Raises:

  • HTTPStatusError

    If the request is not a success or any error that's not a '405' status code.

Returns:

  • TogglTracker | None

    A model from cache or the API. None if nothing is running.

Source code in toggl_api/user.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def current(self, *, refresh: bool = True) -> TogglTracker | None:
    """Get current running tracker. Returns None if no tracker is running.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#get-get-current-time-entry)

    Examples:
        >>> user_endpoint.current()
        None

        >>> user_endpoint.current(refresh=True)
        TogglTracker(...)

    Args:
        refresh: Whether to check the remote API for running trackers.
            If 'refresh' is True it will check if there are any other running
            trackers and update if the 'stop' attribute is None.

    Raises:
        HTTPStatusError: If the request is not a success or any error that's
            not a '405' status code.

    Returns:
        A model from cache or the API. None if nothing is running.
    """

    if not refresh:
        query = list(self.cache.query(TogglQuery("stop", None)))
        return query[0] if query else None

    try:
        response = self.request("/time_entries/current", refresh=refresh)
    except HTTPStatusError as err:
        if not self.re_raise and err.response.status_code == self.TRACKER_NOT_RUNNING:
            log.warning("No tracker is currently running!")
            response = None
        else:
            raise

    self._current_refresh(response)

    return response if isinstance(response, TogglTracker) else None

collect(since: Optional[int | datetime] = None, before: Optional[date] = None, start_date: Optional[date] = None, end_date: Optional[date] = None, *, refresh: bool = False) -> list[TogglTracker]

Get a set of trackers depending on specified parameters.

Official Documentation

Missing meta and include_sharing query flags not supported by wrapper at the moment.

Examples:

>>> collect(since=17300032362, before=date(2024, 11, 27))
>>> collect(refresh=True)
>>> collect(start_date=date(2024, 11, 27), end_date=date(2024, 12, 27))

Parameters:

  • since (Optional[int | datetime], default: None ) –

    Get entries modified since this date using UNIX timestamp. Includes deleted ones if refreshing.

  • before (Optional[date], default: None ) –

    Get entries with start time, before given date (YYYY-MM-DD) or with time in RFC3339 format.

  • start_date (Optional[date], default: None ) –

    Get entries with start time, from start_date YYYY-MM-DD or with time in RFC3339 format. To be used with end_date.

  • end_date (Optional[date], default: None ) –

    Get entries with start time, until end_date YYYY-MM-DD or with time in RFC3339 format. To be used with start_date.

  • refresh (bool, default: False ) –

    Whether to refresh the cache or not.

Raises:

  • DateTimeError

    If the dates are not in the correct ranges.

  • HTTPStatusError

    If the request is not a successful status code.

Returns:

  • list[TogglTracker]

    List of TogglTracker objects that are within specified parameters. Empty if none is matched.

Source code in toggl_api/user.py
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
def collect(
    self,
    since: Optional[int | datetime] = None,
    before: Optional[date] = None,
    start_date: Optional[date] = None,
    end_date: Optional[date] = None,
    *,
    refresh: bool = False,
) -> list[TogglTracker]:
    """Get a set of trackers depending on specified parameters.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#get-timeentries)

    Missing meta and include_sharing query flags not supported by wrapper at
    the moment.

    Examples:
        >>> collect(since=17300032362, before=date(2024, 11, 27))

        >>> collect(refresh=True)

        >>> collect(start_date=date(2024, 11, 27), end_date=date(2024, 12, 27))

    Args:
        since: Get entries modified since this date using UNIX timestamp.
            Includes deleted ones if refreshing.
        before: Get entries with start time, before given date (YYYY-MM-DD)
            or with time in RFC3339 format.
        start_date: Get entries with start time, from start_date YYYY-MM-DD
            or with time in RFC3339 format. To be used with end_date.
        end_date: Get entries with start time, until end_date YYYY-MM-DD or
            with time in RFC3339 format. To be used with start_date.
        refresh: Whether to refresh the cache or not.

    Raises:
        DateTimeError: If the dates are not in the correct ranges.
        HTTPStatusError: If the request is not a successful status code.

    Returns:
       List of TogglTracker objects that are within specified parameters.
            Empty if none is matched.
    """

    if start_date and end_date:
        if end_date < start_date:
            msg = "end_date must be after the start_date!"
            raise DateTimeError(msg)
        if start_date > datetime.now(tz=timezone.utc):
            msg = "start_date must not be earlier than the current date!"
            raise DateTimeError(msg)

    if not refresh:
        return self._collect_cache(since, before, start_date, end_date)

    params = "/time_entries"
    if since or before:
        if since:
            params += f"?since={get_timestamp(since)}"

        if before:
            params += "&" if since else "?"
            params += f"before={format_iso(before)}"

    elif start_date and end_date:
        params += f"?start_date={format_iso(start_date)}&end_date={format_iso(end_date)}"

    response = self.request(params, refresh=refresh)

    return response if isinstance(response, list) else []

get(tracker_id: int | TogglTracker, *, refresh: bool = False) -> TogglTracker | None

Get a single tracker by ID.

Official Documentation

Parameters:

  • tracker_id (int | TogglTracker) –

    ID of the tracker to get.

  • refresh (bool, default: False ) –

    Whether to refresh the cache or not.

Raises:

  • HTTPStatusError

    If anything thats not a ok or 404 status code is returned.

Returns:

  • TogglTracker | None

    TogglTracker object or None if not found.

Source code in toggl_api/user.py
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
def get(
    self,
    tracker_id: int | TogglTracker,
    *,
    refresh: bool = False,
) -> TogglTracker | None:
    """Get a single tracker by ID.

    [Official Documentation](https://engineering.toggl.com/docs/api/time_entries#get-get-a-time-entry-by-id)

    Args:
        tracker_id: ID of the tracker to get.
        refresh: Whether to refresh the cache or not.

    Raises:
        HTTPStatusError: If anything thats not a *ok* or *404* status code
            is returned.

    Returns:
        TogglTracker object or None if not found.
    """
    if isinstance(tracker_id, TogglTracker):
        tracker_id = tracker_id.id

    if not refresh:
        return self.cache.find_entry({"id": tracker_id})

    try:
        response = self.request(
            f"/time_entries/{tracker_id}",
            refresh=refresh,
        )
    except HTTPStatusError as err:
        if not self.re_raise and err.response.status_code == codes.NOT_FOUND:
            log.warning("Tracker with id %s does not exist!", tracker_id)
            return None
        raise

    return response

verify_authentication(auth: BasicAuth) -> bool staticmethod

Check if user is correctly authenticated with the Toggl API.

Official Documentation

Examples:

>>> UserEndpoint.verify_authentication(auth)
True
>>> auth = generate_authentication()
>>> UserEndpoint.verify_authentication(auth)
True

Parameters:

  • auth (BasicAuth) –

    Basic authentication object either created manually or one of the provided authentication utilities.

Raises:

  • HTTPStatusError

    If anything that is an error that is not a FORBIDDEN code.

Returns:

  • bool

    True if successfully verified authentication else False.

Source code in toggl_api/user.py
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
@staticmethod
def verify_authentication(auth: BasicAuth) -> bool:
    """Check if user is correctly authenticated with the Toggl API.

    [Official Documentation](https://engineering.toggl.com/docs/api/me#get-logged)

    Examples:
        >>> UserEndpoint.verify_authentication(auth)
        True

        >>> auth = generate_authentication()
        >>> UserEndpoint.verify_authentication(auth)
        True

    Args:
        auth: Basic authentication object either created manually or one
            of the provided authentication utilities.

    Raises:
        HTTPStatusError: If anything that is an error that is not a FORBIDDEN code.

    Returns:
        True if successfully verified authentication else False.
    """
    try:
        httpx.get(TogglEndpoint.BASE_ENDPOINT + "me/logged", auth=auth).raise_for_status()
    except HTTPStatusError as err:
        log.critical("Failed to verify authentication!")
        log.exception("%s")
        if err.response.status_code != codes.FORBIDDEN:
            raise

        return False

    return True

get_details() -> dict[str, Any]

Returns details for the current user.

Official Documentation

Raises:

  • HTTPStatusError

    If the request is not a successful status code.

Returns:

  • dict[str, Any]

    User details in a raw dictionary.

Source code in toggl_api/user.py
315
316
317
318
319
320
321
322
323
324
325
326
def get_details(self) -> dict[str, Any]:
    """Returns details for the current user.

    [Official Documentation](https://engineering.toggl.com/docs/api/me#get-me)

    Raises:
        HTTPStatusError: If the request is not a successful status code.

    Returns:
        User details in a raw dictionary.
    """
    return TogglEndpoint.request(self, "", raw=True).json()

Types

toggl_api.BulkEditParameter

Bases: TypedDict

Source code in toggl_api/tracker.py
27
28
29
30
class BulkEditParameter(TypedDict):
    op: Literal["add", "remove", "replace"]
    path: str
    value: Any

toggl_api.Edits

Bases: NamedTuple

Source code in toggl_api/tracker.py
33
34
35
class Edits(NamedTuple):
    successes: list[int]
    failures: list[int]