### Example: Tracking Time by Project Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/README.md Fetch projects and worktime entries, build a project name lookup, and sum hours by project. Uses get_projects() and get_worktime(year, month). The example prints date, duration, and project name for entries that have a project. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") # Get all projects and worktime entries projects = await client.get_projects() worktime = await client.get_worktime(year=2026, month=1) # Build a project name lookup project_names = {p.id: p.name_stripped for p in projects} # Sum hours by project for entry in worktime: if entry.has_project: project_name = project_names.get(entry.project_id, "Unknown") print(f"{entry.date}: {entry.duration} on {project_name}") ``` -------------------------------- ### Install timebutler-client via pip Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/README.md Install the package from PyPI. Requires Python >=3.11. ```bash pip install timebutler-client ``` -------------------------------- ### TimebutlerClient instantiation example Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Creates a client instance with a placeholder API key. This is the basic usage for the constructor. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") ``` -------------------------------- ### Example: using get_workdays() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Example usage of the get_workdays() method. Creates a TimebutlerClient with an API key, awaits get_workdays(), then iterates over result.schedules and result.invalid_employees to print schedule details and skipped users. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") result = await client.get_workdays() for schedule in result.schedules: print(f"user {schedule.user_id}: {schedule.employee_number} " f"valid from {schedule.valid_from}, {schedule.weekly_minutes} min/week") for invalid in result.invalid_employees: print(f"skipped {invalid.display_name}: raw employee number {invalid.raw_employee_number!r}") ``` -------------------------------- ### Development quick start commands Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/README.md Commands to set up the dev environment, run tests, linting, formatting checks, and type checking using uv. These are for contributors to the project. ```bash # Create dev environment uv sync --group dev # Run tests uv run --group tests pytest # Run linting uv run --group linting ruff check src/timebutler_client unittests # Run formatting checks uv run --group linting ruff format --check . # Run type checking uv run --group type_check mypy --strict src/timebutler_client uv run --group type_check mypy --strict unittests ``` -------------------------------- ### get_services() usage example Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Shows how to instantiate TimebutlerClient with an API key and call get_services() to fetch services. It then prints the name_stripped of all billable services. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") services = await client.get_services() print([s.name_stripped for s in services if s.billable]) ``` -------------------------------- ### Basic usage: get absences Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/absence.md Shows how to instantiate the TimebutlerClient and fetch absences for a given year. The client requires an API key. The example prints employee number, date range, absence type, and state for each absence. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") absences = await client.get_absences(year=2026) for absence in absences: print( f"{absence.employee_number}: {absence.from_date} - {absence.to_date} " f"({absence.absence_type}, {absence.state})" ) ``` -------------------------------- ### Example usage of get_users() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Shows how to call get_users() with an API key and print each user's employee number, full name, and active status. Requires an API key and async context. ```python import logging from timebutler_client import TimebutlerClient logging.basicConfig(level=logging.WARNING) client = TimebutlerClient(api_key="your-api-key") users = await client.get_users() for user in users: print(f"{user.employee_number}: {user.full_name} (active={user.is_active})") ``` -------------------------------- ### get_projects() usage example Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Shows how to instantiate TimebutlerClient with an API key and call get_projects() to fetch projects. It then filters for active projects and prints their id, name_stripped, and state. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") projects = await client.get_projects() active = [p for p in projects if p.is_active] for project in active: print(f"{project.id}: {project.name_stripped} ({project.state})") ``` -------------------------------- ### Sample Projects CSV data Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-16-api-endpoints-design.md Example CSV payload for projects, including headers and five rows with varied states and comments. ```csv ID of the project;Name;State;Budget in hours;Comments;Creation date 34343;ABC1234 | Kunde ABC - X-Projekt ;Active;0; ;23/08/2024 92343;DEF5678 | DEF Customer - div. Projekte;Active;0; ;08/07/2025 33221;GHI9012 | Großkunde - Super Projekt;Active;0; ;11/08/2025 11998;QWE9877 | Anderer Konzern - Tagesgeschäft;Active;0; ;03/05/2023 33482;FOOB1234 | Jener Laden - Foo Bar (bla bla bla);Inactive;0; ;22/04/2021 ``` -------------------------------- ### Sample Worktime CSV data Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-16-api-endpoints-design.md Example CSV payload for work time entries with seven rows, including timestamps, durations, and project/service IDs. ```csv ID of the work time entry;User ID;Employee number;Date (dd/mm/yyyy);Start time (hh:mm);End time (hh:mm);Working time in seconds;Pause in seconds;State;ID of the project;ID of the service;Comments;Auto stopped 56789012;998877;00123;02/01/2026;07:00;12:30;19800;0;Done;23456;0; ;false 51234567;998877;00123;05/01/2026;07:00;15:00;27000;1800;Done;23456;0; ;false 89012344;998877;00123;05/01/2026;15:00;15:30;1800;0;Done;20267;0; ;false 23457890;998877;00123;06/01/2026;06:00;14:30;28800;1800;Done;23456;0; ;false 65432102;998877;00123;07/01/2026;10:00;10:30;1800;0;Done;20267;0; ;false 88229912;998877;00123;07/01/2026;07:00;10:00;10800;0;Done;23456;0; ;false 28910229;998877;00123;07/01/2026;10:30;17:15;21600;2700;Done;23456;0; ;false ``` -------------------------------- ### Example — filter for one user and validate the month Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Demonstrates passing user_id and an invalid month (13) to trigger ValueError. The exception is caught and printed. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") try: entries = await client.get_worktime(year=2026, month=13, user_id=998877) except ValueError as exc: print(f"Month validation failed: {exc}") ``` -------------------------------- ### Parse workday start date with 'unlimited' mapping Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/types.md Defines a Pydantic BeforeValidator that parses workday schedule start dates, mapping the string 'unlimited' (case-insensitive, whitespace-tolerant) to UNLIMITED_DATE (1900-01-01). Accepts date objects or strict dd/mm/yyyy strings; any other string raises ValueError from _parse_european_date. Used by WorkdaySchedule.valid_from. ```python def _parse_workday_start_date(value: str | date) -> date: """Parse a workday schedule start date, mapping 'unlimited' to UNLIMITED_DATE.""" if isinstance(value, str) and value.strip().lower() == "unlimited": return UNLIMITED_DATE return _parse_european_date(value) #: Date type for workday schedule start dates; accepts 'unlimited' in addition to dd/mm/yyyy. WorkdayStartDate = Annotated[date, BeforeValidator(_parse_workday_start_date)] ``` -------------------------------- ### Non-trivial options: half-day detection and range calculation Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/absence.md Demonstrates using computed properties like has_substitute, is_morning_half_day, is_afternoon_half_day, and to_date_exclusive. The example shows how to detect half-day absences and compute inclusive vs. half-open ranges. Note that workdays is a Decimal from the API. ```python for absence in absences: if absence.has_substitute: print(f"{absence.employee_number} has substitute user {absence.substitute_user_id}") if absence.is_morning_half_day: print(f"{absence.from_date}: morning half-day") elif absence.is_afternoon_half_day: print(f"{absence.from_date}: afternoon half-day") # Inclusive API range vs. half-open Python range days = (absence.to_date_exclusive - absence.from_date).days assert days == absence.workdays or True # workdays is a Decimal from the API ``` -------------------------------- ### get_absences basic call example Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Fetches absences for 2026 and prints each absence's employee number and date range. Requires an API key. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") absences = await client.get_absences(year=2026) for absence in absences: print(f"{absence.employee_number}: {absence.from_date} - {absence.to_date} ({absence.absence_type})") ``` -------------------------------- ### Basic usage: get_worktime Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/worktime.md Creates a TimebutlerClient and fetches worktime entries for a given year and month. Requires an API key. The example prints each entry's date, start/end times, duration, and state. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") entries = await client.get_worktime(year=2026, month=1) for entry in entries: print(f"{entry.date} {entry.start_time}-{entry.end_time}: {entry.duration} ({entry.state})") ``` -------------------------------- ### get_absences error handling example Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Catches ValueError for invalid year, TimebutlerAuthenticationError for HTTP 401/403, TimebutlerRateLimitError with retry_after, and TimebutlerParseError for unparsable responses. ```python from timebutler_client import ( TimebutlerAuthenticationError, TimebutlerClient, TimebutlerParseError, TimebutlerRateLimitError, ) client = TimebutlerClient(api_key="your-api-key") try: absences = await client.get_absences(year=2026) except ValueError as exc: # year outside 1900-2100 print(f"Bad year: {exc}") except TimebutlerAuthenticationError as exc: print(f"API key rejected: {exc}") # HTTP 401/403 except TimebutlerRateLimitError as exc: print(f"Rate limited, retry after {exc.retry_after}s") except TimebutlerParseError as exc: print(f"Unparsable response: {exc}") ``` -------------------------------- ### Basic usage: fetch absences Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/README.md Create a TimebutlerClient with an API key and fetch absences for a given year. The client is async, so await is required. The example prints employee number, from_date, to_date, and absence_type for each absence. ```python from timebutler_client import TimebutlerClient # Create client with your API key client = TimebutlerClient(api_key="your-api-key") # Fetch absences for a specific year absences = await client.get_absences(year=2026) for absence in absences: print(f"{absence.employee_number}: {absence.from_date} - {absence.to_date} ({absence.absence_type})") ``` -------------------------------- ### __repr__ method masking API key Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Returns a string representation with the API key masked as '****'. Example output: TimebutlerClient(base_url='https://app.timebutler.com/api/v1', api_key='****'). ```python def __repr__(self) -> str: return f"TimebutlerClient(base_url={self.base_url!r}, api_key='****')" ``` -------------------------------- ### Catching TimebutlerParseError with client Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/errors.md Shows how to catch TimebutlerParseError when calling client methods like get_workdays(). The exception may have a __cause__ attribute pointing to the underlying KeyError or ValueError from parsing failures. The example prints the exception and its cause if present. ```python from timebutler_client import TimebutlerClient, TimebutlerParseError client = TimebutlerClient(api_key="your-api-key") try: workdays = await client.get_workdays() except TimebutlerParseError as exc: print(f"Unparsable API response: {exc}") cause = exc.__cause__ if cause: print(f" underlying: {type(cause).__name__}: {cause}") ``` -------------------------------- ### TimebutlerClient instantiation with defaults and full configuration Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/configuration.md Shows two ways to create a TimebutlerClient: with only the required api_key (using defaults) and with all configuration options specified. The api_key is the only required argument. ```python # Defaults client = TimebutlerClient(api_key="your-api-key") # Full configuration client = TimebutlerClient( api_key="your-api-key", base_url="https://timebutler.example.internal/api/v1", timeout=10.0, ) ``` -------------------------------- ### Basic usage: fetch and iterate services Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/service.md Shows how to retrieve services with get_services() and print each service's id, stripped name, state, and billable status. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") services = await client.get_services() for service in services: marker = "billable" if service.billable else "not billable" print(f"{service.id}: {service.name_stripped} ({service.state}, {marker})") ``` -------------------------------- ### Basic usage: fetch and iterate projects Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/project.md Shows how to retrieve projects using TimebutlerClient.get_projects() and print each project's id, stripped name, and state. Requires an API key. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") projects = await client.get_projects() for project in projects: print(f"{project.id}: {project.name_stripped} ({project.state})") ``` -------------------------------- ### Catch TimebutlerRateLimitError with backoff Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/errors.md Example of catching TimebutlerRateLimitError and retrying with backoff. Uses asyncio.sleep with the retry_after attribute or a default of 60 seconds. ```python import asyncio from timebutler_client import TimebutlerClient, TimebutlerRateLimitError client = TimebutlerClient(api_key="your-api-key") while True: try: absences = await client.get_absences(year=2026) break except TimebutlerRateLimitError as exc: await asyncio.sleep(exc.retry_after or 60) ``` -------------------------------- ### Join projects with worktime entries to aggregate hours Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/project.md Demonstrates a pattern to aggregate worktime hours per project name. Uses get_projects() and get_worktime(year=2026, month=1), maps project IDs to stripped names, and sums durations for entries with a project. ```python projects = await client.get_projects() worktime = await client.get_worktime(year=2026, month=1) project_names = {p.id: p.name_stripped for p in projects} hourly = {} for entry in worktime: if entry.has_project: name = project_names.get(entry.project_id, "Unknown") hourly[name] = hourly.get(name, 0) + entry.duration.total_seconds() / 3600 for name, hours in sorted(hourly.items(), key=lambda kv: -kv[1]): print(f"{name}: {hours:.1f} h") ``` -------------------------------- ### Catch TimebutlerError with TimebutlerClient Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/errors.md Example of catching TimebutlerError when using TimebutlerClient. The client is instantiated with an API key and get_users() is awaited inside a try/except block. ```python from timebutler_client import TimebutlerClient, TimebutlerError client = TimebutlerClient(api_key="your-api-key") try: users = await client.get_users() except TimebutlerError as exc: print(f"Timebutler client error: {exc}") ``` -------------------------------- ### File structure for timebutler_client and unittests Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-16-api-endpoints-design.md Shows the planned file layout for the client package and unit tests. New files are marked, existing ones noted. ```text src/timebutler_client/ models/ __init__.py # Updated: export Project, Service, WorktimeEntry absence.py # Existing project.py # New service.py # New worktime.py # New client.py # Updated: add get_projects, get_services, get_worktime unittests/ test_absences.py # Existing test_projects.py # New test_services.py # New test_worktime.py # New ``` -------------------------------- ### TimebutlerClient.__init__ Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Constructor for the TimebutlerClient class. Initializes the client with an API key, optional base URL, and timeout. ```APIDOC ## TimebutlerClient.__init__ ### Description Constructor for the TimebutlerClient class. Initializes the client with an API key, optional base URL, and timeout. ### Method Constructor ### Parameters - `api_key` (str) - Required - Timebutler admin API key; sent as the `auth` form field on every request - `base_url` (str) - Optional - Override the API base URL (useful for proxies or test servers). Default: `"https://app.timebutler.com/api/v1"` - `timeout` (float) - Optional - Per-request total timeout in seconds. Default: `30.0` ### Raises - `pydantic.ValidationError` if `base_url`/`timeout` fail Pydantic validation ### Example ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") ``` ``` -------------------------------- ### Sample Services CSV data (header only) Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-16-api-endpoints-design.md CSV payload for services; the sample contains only the header row, indicating an empty response. ```csv ID of the service;Name;State;Billable;Comments;Creation date ``` -------------------------------- ### Basic usage: fetch and print active users Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/user.md Creates a TimebutlerClient with an API key, fetches users, and prints active users with employee number, full name, and email. Requires an API key. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") users = await client.get_users() for user in users: if user.is_active: print(f"{user.employee_number} {user.full_name} <{user.email}>") ``` -------------------------------- ### timebutler_client __all__ exports Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/README.md Complete list of public exports defined in src/timebutler_client/__init__.py. Includes models, client, and exceptions. ```python __all__ = [ "Absence", "EmployeeNumber", "EuropeanDate", "HHMMTime", "InvalidEmployee", "Project", "Service", "TimebutlerAuthenticationError", "TimebutlerClient", "TimebutlerError", "TimebutlerParseError", "TimebutlerRateLimitError", "TimebutlerServerError", "User", "WorkdaySchedule", "WorkdaysResult", "WorktimeEntry", ] ``` -------------------------------- ### Filter billable active services and map to worktime entries Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/service.md Demonstrates filtering services by billable and active status, then mapping service IDs to worktime entries for a given month. ```python services = await client.get_services() billable_active = {s.id: s.name_stripped for s in services if s.billable and s.is_active} worktime = await client.get_worktime(year=2026, month=1) for entry in worktime: if entry.has_service and entry.service_id in billable_active: print(f"{entry.date}: {entry.duration} on service {billable_active[entry.service_id]}") ``` -------------------------------- ### UNLIMITED_DATE sentinel constant Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/types.md Sentinel datetime.date constant representing a workday schedule start date that has been in effect forever. Timebutler returns the string 'unlimited' for such schedules; _parse_workday_start_date maps it to this value (1900-01-01). Exported via from timebutler_client.models.workdays import UNLIMITED_DATE. ```python #: Sentinel for when Timebutler returns "unlimited" as a workday schedule start date. #: "unlimited" means the schedule has been in effect since the very beginning — hence a #: date in the distant past, not the future. UNLIMITED_DATE = date(1900, 1, 1) ``` -------------------------------- ### Dependencies and Pytest Configuration Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-15-timebutler-client-design.md Declares runtime dependencies (aiohttp, pydantic) and test dependencies (pytest, pytest-asyncio, aioresponses). Configures pytest asyncio mode to auto with function-scoped loop. ```toml [project] dependencies = [ "aiohttp>=3.10", "pydantic>=2.5", ] [project.optional-dependencies] tests = [ "pytest==9.0.2", "pytest-asyncio==0.25.0", "aioresponses==0.7.8", ] [tool.pytest.ini_options] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" ``` -------------------------------- ### TimebutlerClient Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Async client for the Timebutler API. It is a Pydantic BaseModel subclass that wraps aiohttp and parses semicolon-delimited CSV responses into typed, frozen Pydantic models. Every public method maps to one HTTP POST endpoint on the Timebutler API; the API rejects GET requests. ```APIDOC ## TimebutlerClient ### Description Async client for the Timebutler API. It is a Pydantic BaseModel subclass that wraps aiohttp and parses semicolon-delimited CSV responses into typed, frozen Pydantic models. Every public method maps to one HTTP POST endpoint on the Timebutler API; the API rejects GET requests. ### Constructor #### Parameters - **base_url** (str) - Optional - Base URL of the Timebutler API; every request is `f"{self.base_url}/"`. Default: `"https://app.timebutler.com/api/v1"` - **timeout** (float) - Optional - Total request timeout in seconds, passed to `aiohttp.ClientTimeout(total=self.timeout)` for each call. Default: `30.0` - **_api_key** (str) - Required - API key; private, so it is never serialized by Pydantic ### Example ```python client = TimebutlerClient(api_key="your-api-key") absences = await client.get_absences(year=2026) ``` ### Notes - A new `aiohttp.ClientSession` is created **per call**; the source comment reads: *"Session is created per-call for simplicity. For high-throughput scenarios, consider passing a shared session or refactoring to use a context manager pattern."* - All requests use `session.post(..., data={...})`; `aiohttp` URL-encodes the dict as form data (`application/x-www-form-urlencoded`). - Every request includes the API key as the form field `auth`; `get_worktime()` additionally sends `year`, `month`, `userid` when provided. ``` -------------------------------- ### Project class definition with Pydantic BaseModel Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/project.md Defines the Project model with fields id, name, state, budget_hours, comments, and creation_date. The model is frozen (ConfigDict(frozen=True)) and uses EuropeanDate for creation_date. ```python class Project(BaseModel): """ Represents a project from Timebutler. Projects are used to categorize worktime entries. The name field is free text set by users and may contain trailing whitespace. """ model_config = ConfigDict(frozen=True) id: int = Field(description="Unique project identifier") name: str = Field(description="Project name (free text, may contain whitespace)") state: str = Field(description="Project state: 'Active' or 'Inactive'") budget_hours: int = Field(default=0, description="Budget in hours, 0 if not set") comments: str | None = Field(default=None, description="Optional comments") creation_date: EuropeanDate = Field(description="Date the project was created") ``` -------------------------------- ### get_projects() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/README.md Retrieves all projects, both active and inactive. This method sends a POST request to the /projects endpoint. ```APIDOC ## POST /projects ### Description Retrieves all projects (active and inactive). ### Method POST ### Endpoint /projects ### Response Returns a list of all projects. ``` -------------------------------- ### Manager lookup and optional dates Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/user.md Fetches users, maps IDs to users, prints managers for users with manager IDs, and prints users who joined in 2025 based on date_of_entry. Uses optional fields. ```python users = await client.get_users() by_id = {u.user_id: u for u in users} for user in users: if not user.manager_user_ids: continue managers = [by_id.get(mid) for mid in user.manager_user_ids] print( f"{user.full_name} reports to: " f"{[m.full_name for m in managers if m is not None]}" ) for user in users: if user.date_of_entry and user.date_of_entry.year == 2025: print(f"{user.full_name} joined in 2025") ``` -------------------------------- ### Response headers for mocks Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-16-api-endpoints-design.md Python dictionary of HTTP response headers used in unit test mocks, including date, content-type, server, set-cookie, and content-disposition. ```python { "date": "Fri, 16 Jan 2026 07:34:40 GMT", "content-type": "text/csv;charset=UTF-8", "server": "nginx/1.24.0", "set-cookie": "lc=de_DE; Max-Age=46656000; Expires=Sat, 10 Jul 2027 07:34:40 GMT; Path=/; HttpOnly", "content-disposition": "attachment;filename=api-result-2026.01.16-8.34.40.csv", } ``` -------------------------------- ### get_services() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/README.md Retrieves all services, both active and inactive. This method sends a POST request to the /services endpoint. ```APIDOC ## POST /services ### Description Retrieves all services (active and inactive). ### Method POST ### Endpoint /services ### Response Returns a list of all services. ``` -------------------------------- ### Basic usage of get_workdays() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/workdays.md Creates a TimebutlerClient with an API key, fetches workdays, and filters schedules for full-time employees (weekly_minutes >= 5*8*60). Prints employee number, weekly minutes, and valid_from for each full-time schedule. ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") result = await client.get_workdays() full_time = [s for s in result.schedules if s.weekly_minutes >= 5 * 8 * 60] for schedule in full_time: print( f"{schedule.employee_number}: {schedule.weekly_minutes} min/week " f"since {schedule.valid_from}" ) ``` -------------------------------- ### TimebutlerClient constructor with api_key, base_url, timeout Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/configuration.md Constructor for the TimebutlerClient Pydantic model. The api_key is required and stored in a private attribute; base_url defaults to the Timebutler API v1 endpoint and timeout defaults to 30.0 seconds. ```python def __init__( self, api_key: str, base_url: str = "https://app.timebutler.com/api/v1", timeout: float = 30.0, ) -> None: super().__init__(base_url=base_url, timeout=timeout) self._api_key = api_key ``` -------------------------------- ### get_users() method definition Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Defines the async get_users() method that fetches all users. Despite the name, it calls a POST endpoint. Raises TimebutlerAuthenticationError, TimebutlerRateLimitError, TimebutlerServerError, or TimebutlerParseError on failure. ```python async def get_users(self) -> list[User]: """ Fetch all users. Returns: List of User objects in API response order; not sorted. Raises: TimebutlerAuthenticationError: If API key is invalid TimebutlerRateLimitError: If rate limit is exceeded TimebutlerServerError: If server returns 5xx error TimebutlerParseError: If response cannot be parsed Note: Despite being named 'get_', this calls a POST endpoint (Timebutler API only accepts POST requests). """ ``` -------------------------------- ### Project class Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/project.md Represents a project from Timebutler. Projects categorize worktime entries. The name field is free text set by users and may contain leading/trailing whitespace; use the name_stripped computed field for a cleaned value. ```APIDOC ## Project ### Description Represents a project from Timebutler. Projects categorize worktime entries. The `name` field is free text set by users and may contain leading/trailing whitespace; use the `name_stripped` computed field for a cleaned value. ### Class Definition ```python class Project(BaseModel): """ Represents a project from Timebutler. Projects are used to categorize worktime entries. The name field is free text set by users and may contain trailing whitespace. """ model_config = ConfigDict(frozen=True) id: int = Field(description="Unique project identifier") name: str = Field(description="Project name (free text, may contain whitespace)") state: str = Field(description="Project state: 'Active' or 'Inactive'") budget_hours: int = Field(default=0, description="Budget in hours, 0 if not set") comments: str | None = Field(default=None, description="Optional comments") creation_date: EuropeanDate = Field(description="Date the project was created") ``` ### Fields | Field | Type | Required | Default | Description | |-------|------|----------|---------|-------------| | `id` | `int` | yes | — | CSV column `ID of the project` | | `name` | `str` | yes | — | CSV column `Name`; free text, may contain whitespace (preserved as-is) | | `state` | `str` | yes | — | CSV column `State`; documented values `'Active'` or `'Inactive'` | | `budget_hours` | `int` | no | `0` | CSV `Budget in hours`; `0` if the cell is empty (`int(...) if row.get(...) else 0`) | | `comments` | `str \| None` | no | `None` | CSV `Comments`, stripped; `None` when empty | | `creation_date` | [`EuropeanDate`](../types.md#europeandate) | yes | — | CSV `Creation date`, strict `dd/mm/yyyy` | The model is frozen (`ConfigDict(frozen=True)`). ### Computed Fields (Properties) | Property | Type | Description | |----------|------|-------------| | `name_stripped` | `str` | `self.name.strip()` — project name without leading/trailing whitespace | | `is_active` | `bool` | `self.state == "Active"` | Both are Pydantic `@computed_field` properties (present in `model_dump()` / `model_dump_json()`). ### CSV Source (parsed by `_parse_projects_csv`) Semicolon-delimited columns consumed: `ID of the project`, `Name`, `State`, `Budget in hours`, `Comments`, `Creation date`. `ID of the project`, `Name`, `State`, `Creation date` are required; missing columns or failed conversions raise `TimebutlerParseError`. See [endpoints.md](../endpoints.md). ### Examples Basic usage: ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") projects = await client.get_projects() for project in projects: print(f"{project.id}: {project.name_stripped} ({project.state})") ``` Non-trivial options — join with worktime entries (project name lookup pattern from the README): ```python projects = await client.get_projects() worktime = await client.get_worktime(year=2026, month=1) project_names = {p.id: p.name_stripped for p in projects} hourly = {} for entry in worktime: if entry.has_project: name = project_names.get(entry.project_id, "Unknown") hourly[name] = hourly.get(name, 0) + entry.duration.total_seconds() / 3600 for name, hours in sorted(hourly.items(), key=lambda kv: -kv[1]): print(f"{name}: {hours:.1f} h") ``` See also: [worktime.md](worktime.md), [types.md](../types.md), [endpoints.md](../endpoints.md). ``` -------------------------------- ### get_projects() method definition Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Defines the async get_projects() method that fetches all projects. It returns a list of Project objects (both active and inactive) and raises TimebutlerAuthenticationError, TimebutlerRateLimitError, TimebutlerServerError, or TimebutlerParseError on failure. Despite the name, it calls a POST endpoint because the Timebutler API only accepts POST requests. ```python async def get_projects(self) -> list[Project]: """ Fetch all projects. Returns: List of Project objects (both active and inactive) Raises: TimebutlerAuthenticationError: If API key is invalid TimebutlerRateLimitError: If rate limit is exceeded TimebutlerServerError: If server returns 5xx error TimebutlerParseError: If response cannot be parsed Note: Despite being named 'get_', this calls a POST endpoint (Timebutler API only accepts POST requests). """ ``` -------------------------------- ### Using timedelta accessors and invalid employees Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/workdays.md Iterates over schedules to print per-day durations (monday, tuesday) and total weekly_duration, then prints warnings for invalid employees with unparsable employee numbers. ```python result = await client.get_workdays() for schedule in result.schedules: print( f"user {schedule.user_id}: Mon={schedule.monday}, " f"Tue={schedule.tuesday}, total={schedule.weekly_duration}" ) for invalid in result.invalid_employees: print( f"WARNING: {invalid.display_name} (user_id={invalid.user_id}) has " f"unparsable employee number {invalid.raw_employee_number!r}" ) ``` -------------------------------- ### get_users() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/README.md Retrieves all users. This method sends a POST request to the /users endpoint. ```APIDOC ## POST /users ### Description Retrieves all users. ### Method POST ### Endpoint /users ### Response Returns a list of all users. ``` -------------------------------- ### get_services() method definition Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Defines the async get_services() method that fetches all services. It returns a list of Service objects (both active and inactive) and raises TimebutlerAuthenticationError, TimebutlerRateLimitError, TimebutlerServerError, or TimebutlerParseError on failure. Despite the name, it calls a POST endpoint because the Timebutler API only accepts POST requests. ```python async def get_services(self) -> list[Service]: """ Fetch all services. Returns: List of Service objects (both active and inactive) Raises: TimebutlerAuthenticationError: If API key is invalid TimebutlerRateLimitError: If rate limit is exceeded TimebutlerServerError: If server returns 5xx error TimebutlerParseError: If response cannot be parsed Note: Despite being named 'get_', this calls a POST endpoint (Timebutler API only accepts POST requests). """ ``` -------------------------------- ### Catching TimebutlerServerError with client Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/errors.md Shows how to catch TimebutlerServerError when calling client methods like get_projects(). The exception includes the HTTP status code, accessible via exc.status_code. Requires an API key for TimebutlerClient. ```python from timebutler_client import TimebutlerClient, TimebutlerServerError client = TimebutlerClient(api_key="your-api-key") try: projects = await client.get_projects() except TimebutlerServerError as exc: print(f"Server failed with HTTP {exc.status_code}: {exc}") ``` -------------------------------- ### TimebutlerClient.get_services() Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/service.md Returns a list of Service objects, including both active and inactive services. This method is part of the TimebutlerClient and is used to retrieve all services from Timebutler. ```APIDOC ## TimebutlerClient.get_services() ### Description Retrieves all services from Timebutler, returning a list of Service objects. Both active and inactive services are included. ### Method GET (conceptual - actual method is a client method) ### Endpoint Not specified (client method) ### Parameters None ### Return Value - **list[Service]** - List of Service objects ### Example ```python from timebutler_client import TimebutlerClient client = TimebutlerClient(api_key="your-api-key") services = await client.get_services() for service in services: marker = "billable" if service.billable else "not billable" print(f"{service.id}: {service.name_stripped} ({service.state}, {marker})") ``` ``` -------------------------------- ### Module __all__ for timebutler_client.exceptions Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/exceptions.md Defines the public exception classes exported by the module. Import these from timebutler_client.exceptions or from the top-level package. ```python __all__ = [ "TimebutlerAuthenticationError", "TimebutlerError", "TimebutlerParseError", "TimebutlerRateLimitError", "TimebutlerServerError", ] ``` -------------------------------- ### POST /projects Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/endpoints.md Retrieves project data. The client method get_projects() sends a POST request to this endpoint and parses the CSV response into Project objects, returning both active and inactive projects. ```APIDOC ## POST /projects ### Description Retrieves project data. The client method `get_projects()` sends a POST request to this endpoint and parses the CSV response into `Project` objects, returning both active and inactive projects. ### Method POST ### Endpoint /projects ### Parameters #### Form Parameters - **auth** (str) - Required - Admin API key ### Response #### Success Response (200) CSV response with columns parsed into `Project` fields: - **ID of the project** - Parsed into `id: int` - **Name** - Parsed into `name: str` (whitespace preserved) - **State** - Parsed into `state: str` (`'Active'` or `'Inactive'`) - **Budget in hours** - Parsed into `budget_hours: int` (default `0` if empty) - **Comments** - Parsed into `comments: str | None` (stripped; `None` if empty) - **Creation date** - Parsed into `creation_date` (EuropeanDate, `dd/mm/yyyy`) ``` -------------------------------- ### TimebutlerClient.__repr__ Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/client.md Returns a string representation of the client with the API key masked as '****'. ```APIDOC ## TimebutlerClient.__repr__ ### Description Returns a string representation of the client with the API key masked as '****'. ### Method Method ### Returns - `str` - String representation, e.g., `TimebutlerClient(base_url='https://app.timebutler.com/api/v1', api_key='****')` ``` -------------------------------- ### Service class definition with Pydantic fields Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/service.md Defines the Service model with fields id, name, state, billable, comments, and creation_date. The model is frozen and uses ConfigDict(frozen=True). ```python class Service(BaseModel): """ Represents a service from Timebutler. Services are used to categorize worktime entries by type of work. """ model_config = ConfigDict(frozen=True) id: int = Field(description="Unique service identifier") name: str = Field(description="Service name (free text, may contain whitespace)") state: str = Field(description="Service state: 'Active' or 'Inactive'") billable: bool = Field(default=False, description="Whether the service is billable") comments: str | None = Field(default=None, description="Optional comments") creation_date: EuropeanDate = Field(description="Date the service was created") ``` -------------------------------- ### Aggregate overtime per employee Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/worktime.md Fetches worktime entries for a month and aggregates net hours (excluding pauses) per employee, only for entries with state "Done". Uses a defaultdict to accumulate hours and prints sorted results. ```python from collections import defaultdict entries = await client.get_worktime(year=2026, month=6) per_employee = defaultdict(lambda: 0.0) for entry in entries: if entry.state == "Done": net_hours = (entry.duration - entry.pause).total_seconds() / 3600 per_employee[entry.employee_number] += net_hours for employee_number, hours in sorted(per_employee.items()): print(f"{employee_number}: {hours:.2f} h") ``` -------------------------------- ### TimebutlerAuthenticationError Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/exceptions.md Raised when API authentication fails (HTTP 401/403). Indicates the admin API key was rejected. ```APIDOC ## TimebutlerAuthenticationError ### Description Raised when API authentication fails (HTTP 401/403). Indicates the admin API key was rejected. ### Class `TimebutlerAuthenticationError(TimebutlerError)` ### Import Path - `from timebutler_client.exceptions import TimebutlerAuthenticationError` - `from timebutler_client import TimebutlerAuthenticationError` ### Inherits From - `TimebutlerError` ### Raised By - `TimebutlerClient._check_response` when the API responds with HTTP 401 or 403. ### Message - `"Invalid API key"` ``` -------------------------------- ### TimebutlerClient Class Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/docs/plans/2026-01-15-timebutler-client-design.md Async client for the Timebutler API using aiohttp. Stores API key as PrivateAttr and creates a session per call. get_absences uses POST despite the name. ```python class TimebutlerClient(BaseModel): """Async client for the Timebutler API.""" base_url: str = "https://app.timebutler.com/api/v1" _api_key: str = PrivateAttr() def __init__(self, api_key: str, base_url: str = "https://app.timebutler.com/api/v1") -> None: ... async def get_absences(self, year: int) -> list[Absence]: """ Fetch absences for a given year. Note: Despite being named 'get_', this calls a POST endpoint (Timebutler API only accepts POST requests). """ ... ``` -------------------------------- ### TimebutlerError Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/exceptions.md Base exception for all Timebutler client errors. Catch this to handle all client-specific failures without importing each subclass. ```APIDOC ## TimebutlerError ### Description Base exception for Timebutler client errors. Catch this to handle all Timebutler client failures without importing each subclass. ### Class `TimebutlerError(Exception)` ### Import Path - `from timebutler_client.exceptions import TimebutlerError` - `from timebutler_client import TimebutlerError` ### Inherits From - `Exception` ### Attributes - No additional members beyond `Exception`. ``` -------------------------------- ### TimebutlerAuthenticationError class Source: https://github.com/hochfrequenz/timebutler_client.py/blob/main/_autodocs/api-reference/exceptions.md Raised when API authentication fails (HTTP 401/403). Message is "Invalid API key". Indicates the admin API key was rejected. ```python class TimebutlerAuthenticationError(TimebutlerError): """Raised when API authentication fails (HTTP 401/403).""" ```