Examples
All Tracker, Client, Project & Tag endpoints will have most of these methods:
- collect: Gathering models.
- get: Retrieving a model.
- delete: Deleting a model.
- edit: Editing a model.
- add: Creating a new model.
Info
With environment variables setup correctly.
Tracker Example¶
from datetime import timedelta
from pathlib import Path
from toggl_api import (
TrackerBody,
TrackerEndpoint,
generate_authentication,
)
from toggl_api.meta.cache.sqlite_cache import SqliteCache
WORKSPACE_ID = 2313123123
AUTH = generate_authentication()
cache = SqliteCache(Path("cache"), timedelta(hours=24))
endpoint = TrackerEndpoint(WORKSPACE_ID, AUTH, cache)
body = TrackerBody("My First Tracker", tags=["My First Tag"])
tracker = endpoint.add(body)
print(tracker)
Outputs:
>>> TogglTracker(
id=3482231563,
name="My First Tracker",
workspace=2313123123,
start=datetime.datetime(2024, 6, 10, 14, 59, 20, tzinfo=datetime.timezone.utc),
duration=datetime.timedelta(seconds=1, microseconds=179158),
stop=None,
project=None,
tags=[],
)
Project Example¶
Info
Using an existing togglrc file.
from datetime import timedelta
from pathlib import Path
from toggl_api import (
JSONCache,
ProjectBody,
ProjectEndpoint,
)
from toggl_api.config import retrieve_togglrc_workspace_id, use_togglrc
WORKSPACE_ID = retrieve_togglrc_workspace_id()
AUTH = use_togglrc()
cache = JSONCache(Path("cache"), timedelta(hours=24))
endpoint = ProjectEndpoint(WORKSPACE_ID, AUTH, cache)
color = ProjectEndpoint.get_color("red")
body = ProjectBody(
"My First Project",
client_name="My First Client",
color=color,
)
project = endpoint.add(body)
print(project)
Outputs:
>>> TogglProject(
id=203366783,
name='My First Project',
workspace=2313123123,
color='#d92b2b',
client=65298912,
active=True,
)
Report Example¶
- With Plotly, Pandas and Kaleidoscope installed.
import os
import time
from collections import defaultdict
from datetime import date, datetime
import pandas as pd
import plotly.express as px
from toggl_api import generate_authentication
from toggl_api.reports import DetailedReportEndpoint, ReportBody
# Setup Endpoint
WORKSPACE_ID = int(os.environ.get("TOGGL_WORKSPACE_ID", 0))
AUTH = generate_authentication()
detailed_report_endpoint = DetailedReportEndpoint(WORKSPACE_ID, AUTH)
start_date = date(2024, 1, 1)
end_date = date(2024, 11, 9)
body = ReportBody(
start_date=start_date,
end_date=end_date,
project_ids=[202484947],
)
# Retrieve Data
print("Initial Request")
first = detailed_report_endpoint.search_time_entries(body)
next_page = first.next_options()
content = first.result
while next_page.next_id is not None and next_page.next_row is not None:
time.sleep(1)
print(f"Requesting id {next_page.next_id} and row {next_page.next_row}")
search = detailed_report_endpoint.search_time_entries(body, next_page)
content.extend(search.result)
next_page = search.next_options()
# Process Target Data
aggregrate: defaultdict[str, int] = defaultdict(lambda: 0)
for tracker in content:
time_data = tracker["time_entries"][0]
start = datetime.strptime(time_data["at"], "%Y-%m-%dT%H:%M:%S%z")
aggregrate[start.strftime("%B")] += time_data["seconds"] // 60
# Plot & View Data
monthly_minutes = pd.DataFrame(
aggregrate.items(),
index=aggregrate.keys(),
columns=["month", "minutes"],
)
fig = px.bar(
monthly_minutes,
"month",
"minutes",
title="Total recorded monthly minutes spent on Toggl API Wrapper in 2024",
)
fig.show()
fig.write_image("total-minutes-may-to-october-2024.svg")
Outputs:
Logging Example¶
import logging
import os
from pathlib import Path
from toggl_api import JSONCache, UserEndpoint, generate_authentication
logging.basicConfig(
format="%(levelname)s [%(asctime)s] %(name)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO,
)
WORKSPACE_ID = int(os.environ.get("TOGGL_WORKSPACE_ID", 0))
AUTH = generate_authentication()
cache = JSONCache(Path("cache"))
endpoint = UserEndpoint(WORKSPACE_ID, AUTH, cache)
endpoint.check_authentication()
Outputs:
INFO [2024-10-15 12:08:21] toggl-api-wrapper - Detected an api token as authentication.
INFO [2024-10-15 12:08:21] httpx - HTTP Request: GET https://api.track.toggl.com/api/v9/me/logged "HTTP/1.1 200 OK"