zammad-python-client 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. zammad_python_client-0.1.1/LICENSE +21 -0
  2. zammad_python_client-0.1.1/PKG-INFO +127 -0
  3. zammad_python_client-0.1.1/README.md +96 -0
  4. zammad_python_client-0.1.1/pyproject.toml +62 -0
  5. zammad_python_client-0.1.1/setup.cfg +4 -0
  6. zammad_python_client-0.1.1/src/zammad/__init__.py +56 -0
  7. zammad_python_client-0.1.1/src/zammad/client.py +99 -0
  8. zammad_python_client-0.1.1/src/zammad/exceptions.py +50 -0
  9. zammad_python_client-0.1.1/src/zammad/py.typed +0 -0
  10. zammad_python_client-0.1.1/src/zammad/resources/__init__.py +22 -0
  11. zammad_python_client-0.1.1/src/zammad/resources/base.py +114 -0
  12. zammad_python_client-0.1.1/src/zammad/resources/generated.py +3297 -0
  13. zammad_python_client-0.1.1/src/zammad/resources/knowledge_base.py +173 -0
  14. zammad_python_client-0.1.1/src/zammad/resources/people.py +96 -0
  15. zammad_python_client-0.1.1/src/zammad/resources/tickets.py +230 -0
  16. zammad_python_client-0.1.1/src/zammad/transport.py +284 -0
  17. zammad_python_client-0.1.1/src/zammad/types.py +221 -0
  18. zammad_python_client-0.1.1/src/zammad_python_client.egg-info/PKG-INFO +127 -0
  19. zammad_python_client-0.1.1/src/zammad_python_client.egg-info/SOURCES.txt +23 -0
  20. zammad_python_client-0.1.1/src/zammad_python_client.egg-info/dependency_links.txt +1 -0
  21. zammad_python_client-0.1.1/src/zammad_python_client.egg-info/requires.txt +10 -0
  22. zammad_python_client-0.1.1/src/zammad_python_client.egg-info/top_level.txt +1 -0
  23. zammad_python_client-0.1.1/tests/test_generated.py +72 -0
  24. zammad_python_client-0.1.1/tests/test_resources.py +141 -0
  25. zammad_python_client-0.1.1/tests/test_transport.py +124 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stefan Schulte-Ortbeck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: zammad-python-client
3
+ Version: 0.1.1
4
+ Summary: A typed Python client for the Zammad REST API
5
+ Author-email: Stefan Schulte-Ortbeck <info@codefighters.de>
6
+ License: MIT
7
+ Project-URL: Repository, https://gitlab.codefighters.de/python/zammad-python-client
8
+ Project-URL: Changelog, https://gitlab.codefighters.de/python/zammad-python-client/-/blob/main/CHANGELOG.md
9
+ Keywords: zammad,helpdesk,api,client
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: requests>=2.28.0
23
+ Provides-Extra: dotenv
24
+ Requires-Dist: python-dotenv>=1.0.0; extra == "dotenv"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.0; extra == "dev"
27
+ Requires-Dist: responses>=0.23; extra == "dev"
28
+ Requires-Dist: mypy>=1.8; extra == "dev"
29
+ Requires-Dist: types-requests; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # zammad-python-client
33
+
34
+ A typed Python client for the [Zammad](https://zammad.org) REST API. `requests`
35
+ underneath, `py.typed`, no other dependencies. Built for Zammad 7.x and used by
36
+ [`python/zammad-mcp`](https://gitlab.codefighters.de/python/zammad-mcp).
37
+
38
+ Two layers:
39
+
40
+ - **Curated**: `client.tickets`, `client.ticket_articles`, `client.tags`,
41
+ `client.time_accountings`, `client.users`, `client.organizations`,
42
+ `client.groups`, `client.ticket_states`, `client.ticket_priorities`,
43
+ `client.knowledge_base`, plus plain CRUD collections (`client.text_modules`,
44
+ `client.macros`, `client.slas`, ...). One call per question, sensible defaults.
45
+ - **Complete**: `client.api.<controller>.<action>()`, one method per route of
46
+ Zammad's own routing — 612 routes, 118 controllers, generated from
47
+ `config/routes/*.rb` of the pinned Zammad version. See
48
+ [`docs/endpoints.md`](docs/endpoints.md). Nothing the web UI can do is out of
49
+ reach, including the knowledge base, two-factor, channels and integrations.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ pip install zammad-python-client
55
+ ```
56
+
57
+ Published to PyPI on every tag; the same wheel also lands in this project's GitLab
58
+ package registry for internal CI. From a checkout: `pip install -e ".[dev]"`.
59
+
60
+ ## Use
61
+
62
+ ```python
63
+ from zammad import ZammadClient
64
+
65
+ c = ZammadClient("https://zammad.example.com", token="...") # Authorization: Token token=...
66
+
67
+ c.version() # "7.2.2"
68
+ c.users.current() # the token's user
69
+ open_ = c.tickets.search_tickets("state.name:open owner.login:me", limit=20)
70
+ t = c.tickets.get(42, expand=True) # names next to ids
71
+ c.ticket_articles.by_ticket(42)
72
+ c.ticket_articles.add(42, "<p>Looked at it.</p>") # internal note (default)
73
+ c.ticket_articles.add(42, "<p>Fixed.</p>", article_type="email", internal=False, to="customer@example.com")
74
+ c.time_accountings.book(42, 15) # unit is instance config
75
+ c.tags.add_to(42, "billing")
76
+
77
+ kb = c.knowledge_base.init() # bases, locales, categories, answers as assets
78
+ c.knowledge_base.search("vpn", flavor="agent")
79
+ a = c.knowledge_base.create_answer(1, category_id=3, title="VPN", body_html="<p>…</p>", kb_locale_id=1)
80
+ c.knowledge_base.set_internal(1, a["id"]) # draft -> internal (agents only)
81
+
82
+ # Everything else: the generated layer, named after Zammad's controllers and actions.
83
+ c.api.settings.index_by_area("Ticket::Base")
84
+ c.api.user_two_factors.personal_configuration()
85
+ c.api.channels_email.index()
86
+ ```
87
+
88
+ Acting as another user (needs `admin.user`): every method takes
89
+ `on_behalf_of="login-or-email-or-id"`, sent as Zammad's `From` header.
90
+
91
+ Pagination: `list(page=, per_page=)` is one page, `iter_all()` / `list_all()`
92
+ walk pages (Zammad returns bare arrays without a total, so a short page ends the
93
+ walk). `expand=True` adds related names next to the `*_id` fields.
94
+
95
+ ## Errors
96
+
97
+ `ZammadError` covers everything; `ZammadAuthError` (401), `ZammadPermissionError`
98
+ (403, the token lacks a permission), `ZammadNotFoundError` (404, which Zammad also
99
+ uses for "not visible to you") and `ZammadRateLimitError` (429 that could not be
100
+ waited out; `retry_after` when known) narrow it.
101
+
102
+ ## Keeping up with Zammad
103
+
104
+ ```bash
105
+ scripts/extract-routes.py --ref stable # or --zammad /path/to/checkout
106
+ scripts/generate-resources.py
107
+ pytest
108
+ ```
109
+
110
+ `docs/routes.json` records the Zammad version it came from. Rails `resources`
111
+ blocks (knowledge base, two-factor, checklists, …) are expanded by hand in
112
+ `scripts/extract-routes.py`; the script says which route files contain such
113
+ blocks so a new one is not missed. CI fails when `generated.py` and
114
+ `docs/routes.json` disagree.
115
+
116
+ ## Development
117
+
118
+ ```bash
119
+ uv venv && uv pip install -e ".[dev]"
120
+ pytest -q # mocks only, never the network
121
+ mypy
122
+ scripts/verify-live.py # read-only, needs ZAMMAD_URL + ZAMMAD_TOKEN in .env
123
+ ```
124
+
125
+ Releases: bump `__version__` in `src/zammad/__init__.py`, update the changelog,
126
+ tag `vX.Y.Z`; CI publishes to PyPI (needs the `PYPI_TOKEN` CI variable) and to the
127
+ project's GitLab registry.
@@ -0,0 +1,96 @@
1
+ # zammad-python-client
2
+
3
+ A typed Python client for the [Zammad](https://zammad.org) REST API. `requests`
4
+ underneath, `py.typed`, no other dependencies. Built for Zammad 7.x and used by
5
+ [`python/zammad-mcp`](https://gitlab.codefighters.de/python/zammad-mcp).
6
+
7
+ Two layers:
8
+
9
+ - **Curated**: `client.tickets`, `client.ticket_articles`, `client.tags`,
10
+ `client.time_accountings`, `client.users`, `client.organizations`,
11
+ `client.groups`, `client.ticket_states`, `client.ticket_priorities`,
12
+ `client.knowledge_base`, plus plain CRUD collections (`client.text_modules`,
13
+ `client.macros`, `client.slas`, ...). One call per question, sensible defaults.
14
+ - **Complete**: `client.api.<controller>.<action>()`, one method per route of
15
+ Zammad's own routing — 612 routes, 118 controllers, generated from
16
+ `config/routes/*.rb` of the pinned Zammad version. See
17
+ [`docs/endpoints.md`](docs/endpoints.md). Nothing the web UI can do is out of
18
+ reach, including the knowledge base, two-factor, channels and integrations.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install zammad-python-client
24
+ ```
25
+
26
+ Published to PyPI on every tag; the same wheel also lands in this project's GitLab
27
+ package registry for internal CI. From a checkout: `pip install -e ".[dev]"`.
28
+
29
+ ## Use
30
+
31
+ ```python
32
+ from zammad import ZammadClient
33
+
34
+ c = ZammadClient("https://zammad.example.com", token="...") # Authorization: Token token=...
35
+
36
+ c.version() # "7.2.2"
37
+ c.users.current() # the token's user
38
+ open_ = c.tickets.search_tickets("state.name:open owner.login:me", limit=20)
39
+ t = c.tickets.get(42, expand=True) # names next to ids
40
+ c.ticket_articles.by_ticket(42)
41
+ c.ticket_articles.add(42, "<p>Looked at it.</p>") # internal note (default)
42
+ c.ticket_articles.add(42, "<p>Fixed.</p>", article_type="email", internal=False, to="customer@example.com")
43
+ c.time_accountings.book(42, 15) # unit is instance config
44
+ c.tags.add_to(42, "billing")
45
+
46
+ kb = c.knowledge_base.init() # bases, locales, categories, answers as assets
47
+ c.knowledge_base.search("vpn", flavor="agent")
48
+ a = c.knowledge_base.create_answer(1, category_id=3, title="VPN", body_html="<p>…</p>", kb_locale_id=1)
49
+ c.knowledge_base.set_internal(1, a["id"]) # draft -> internal (agents only)
50
+
51
+ # Everything else: the generated layer, named after Zammad's controllers and actions.
52
+ c.api.settings.index_by_area("Ticket::Base")
53
+ c.api.user_two_factors.personal_configuration()
54
+ c.api.channels_email.index()
55
+ ```
56
+
57
+ Acting as another user (needs `admin.user`): every method takes
58
+ `on_behalf_of="login-or-email-or-id"`, sent as Zammad's `From` header.
59
+
60
+ Pagination: `list(page=, per_page=)` is one page, `iter_all()` / `list_all()`
61
+ walk pages (Zammad returns bare arrays without a total, so a short page ends the
62
+ walk). `expand=True` adds related names next to the `*_id` fields.
63
+
64
+ ## Errors
65
+
66
+ `ZammadError` covers everything; `ZammadAuthError` (401), `ZammadPermissionError`
67
+ (403, the token lacks a permission), `ZammadNotFoundError` (404, which Zammad also
68
+ uses for "not visible to you") and `ZammadRateLimitError` (429 that could not be
69
+ waited out; `retry_after` when known) narrow it.
70
+
71
+ ## Keeping up with Zammad
72
+
73
+ ```bash
74
+ scripts/extract-routes.py --ref stable # or --zammad /path/to/checkout
75
+ scripts/generate-resources.py
76
+ pytest
77
+ ```
78
+
79
+ `docs/routes.json` records the Zammad version it came from. Rails `resources`
80
+ blocks (knowledge base, two-factor, checklists, …) are expanded by hand in
81
+ `scripts/extract-routes.py`; the script says which route files contain such
82
+ blocks so a new one is not missed. CI fails when `generated.py` and
83
+ `docs/routes.json` disagree.
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ uv venv && uv pip install -e ".[dev]"
89
+ pytest -q # mocks only, never the network
90
+ mypy
91
+ scripts/verify-live.py # read-only, needs ZAMMAD_URL + ZAMMAD_TOKEN in .env
92
+ ```
93
+
94
+ Releases: bump `__version__` in `src/zammad/__init__.py`, update the changelog,
95
+ tag `vX.Y.Z`; CI publishes to PyPI (needs the `PYPI_TOKEN` CI variable) and to the
96
+ project's GitLab registry.
@@ -0,0 +1,62 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zammad-python-client"
7
+ dynamic = ["version"]
8
+ description = "A typed Python client for the Zammad REST API"
9
+ authors = [{name = "Stefan Schulte-Ortbeck", email = "info@codefighters.de"}]
10
+ readme = "README.md"
11
+ license = {text = "MIT"}
12
+ keywords = ["zammad", "helpdesk", "api", "client"]
13
+ dependencies = [
14
+ "requests>=2.28.0",
15
+ ]
16
+ # Keep in lockstep with the matrix in .gitlab-ci.yml. Same floor as
17
+ # billomat-python-client, for the same reason (3.10 is EOL in October 2026).
18
+ requires-python = ">=3.11"
19
+ classifiers = [
20
+ "Development Status :: 3 - Alpha",
21
+ "Intended Audience :: Developers",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
28
+ "Typing :: Typed",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dotenv = ["python-dotenv>=1.0.0"]
33
+ dev = [
34
+ "pytest>=7.0",
35
+ "responses>=0.23",
36
+ "mypy>=1.8",
37
+ "types-requests",
38
+ ]
39
+
40
+ [project.urls]
41
+ Repository = "https://gitlab.codefighters.de/python/zammad-python-client"
42
+ Changelog = "https://gitlab.codefighters.de/python/zammad-python-client/-/blob/main/CHANGELOG.md"
43
+
44
+ [tool.setuptools.dynamic]
45
+ # Single source of truth; the publish job refuses a tag that does not match it.
46
+ version = {attr = "zammad.__version__"}
47
+
48
+ [tool.setuptools.packages.find]
49
+ where = ["src"]
50
+
51
+ [tool.setuptools.package-data]
52
+ zammad = ["py.typed"]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
56
+
57
+ [tool.mypy]
58
+ python_version = "3.11"
59
+ files = ["src/zammad"]
60
+ warn_unused_ignores = true
61
+ warn_redundant_casts = true
62
+ warn_unreachable = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,56 @@
1
+ """A typed Python client for the Zammad REST API."""
2
+
3
+ import logging
4
+
5
+ from .client import ZammadClient
6
+ from .exceptions import (
7
+ ZammadAuthError,
8
+ ZammadError,
9
+ ZammadNotFoundError,
10
+ ZammadPermissionError,
11
+ ZammadRateLimitError,
12
+ )
13
+ from .resources import Api, Endpoint, Resource
14
+ from .transport import Transport
15
+ from .types import (
16
+ GenericDict,
17
+ GroupDict,
18
+ KnowledgeBaseAnswerDict,
19
+ KnowledgeBaseCategoryDict,
20
+ OrganizationDict,
21
+ TicketArticleDict,
22
+ TicketDict,
23
+ TicketPriorityDict,
24
+ TicketStateDict,
25
+ TimeAccountingDict,
26
+ UserDict,
27
+ )
28
+
29
+ __version__ = "0.1.1"
30
+
31
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
32
+
33
+ __all__ = [
34
+ "ZammadClient",
35
+ "ZammadError",
36
+ "ZammadAuthError",
37
+ "ZammadPermissionError",
38
+ "ZammadNotFoundError",
39
+ "ZammadRateLimitError",
40
+ "Transport",
41
+ "Endpoint",
42
+ "Resource",
43
+ "Api",
44
+ "GenericDict",
45
+ "TicketDict",
46
+ "TicketArticleDict",
47
+ "UserDict",
48
+ "OrganizationDict",
49
+ "GroupDict",
50
+ "TicketStateDict",
51
+ "TicketPriorityDict",
52
+ "TimeAccountingDict",
53
+ "KnowledgeBaseAnswerDict",
54
+ "KnowledgeBaseCategoryDict",
55
+ "__version__",
56
+ ]
@@ -0,0 +1,99 @@
1
+ """Composition root: one ``ZammadClient`` per instance and credential."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ import requests
8
+
9
+ from .resources import (
10
+ Api,
11
+ Groups,
12
+ KnowledgeBase,
13
+ Organizations,
14
+ Resource,
15
+ Roles,
16
+ Tags,
17
+ TicketArticles,
18
+ TicketPriorities,
19
+ Tickets,
20
+ TicketStates,
21
+ TimeAccountings,
22
+ Users,
23
+ )
24
+ from .transport import Transport
25
+
26
+
27
+ class ZammadClient:
28
+ """Entry point.
29
+
30
+ The curated attributes (``tickets``, ``users``, ...) are the ergonomic
31
+ layer. ``api`` exposes every controller of the instance's routing with one
32
+ method per route (``client.api.settings.index_by_area(...)``), so nothing
33
+ the UI can do is out of reach -- see docs/endpoints.md.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ url: str,
39
+ token: Optional[str] = None,
40
+ *,
41
+ bearer: Optional[str] = None,
42
+ username: Optional[str] = None,
43
+ password: Optional[str] = None,
44
+ session: Optional[requests.Session] = None,
45
+ timeout: float = 30.0,
46
+ max_attempts: int = 3,
47
+ ) -> None:
48
+ self.transport = Transport(
49
+ url,
50
+ token=token,
51
+ bearer=bearer,
52
+ username=username,
53
+ password=password,
54
+ session=session,
55
+ timeout=timeout,
56
+ max_attempts=max_attempts,
57
+ )
58
+ t = self.transport
59
+ # Curated
60
+ self.tickets = Tickets(t)
61
+ self.ticket_articles = TicketArticles(t)
62
+ self.tags = Tags(t)
63
+ self.time_accountings = TimeAccountings(t)
64
+ self.users = Users(t)
65
+ self.organizations = Organizations(t)
66
+ self.groups = Groups(t)
67
+ self.roles = Roles(t)
68
+ self.ticket_states = TicketStates(t)
69
+ self.ticket_priorities = TicketPriorities(t)
70
+ self.knowledge_base = KnowledgeBase(t)
71
+ # Plain CRUD collections that need nothing beyond list/get/create/update/delete.
72
+ self.text_modules: Resource[Dict[str, Any]] = Resource(t, "/text_modules")
73
+ self.macros: Resource[Dict[str, Any]] = Resource(t, "/macros")
74
+ self.overviews: Resource[Dict[str, Any]] = Resource(t, "/overviews")
75
+ self.templates: Resource[Dict[str, Any]] = Resource(t, "/templates")
76
+ self.signatures: Resource[Dict[str, Any]] = Resource(t, "/signatures")
77
+ self.email_addresses: Resource[Dict[str, Any]] = Resource(t, "/email_addresses")
78
+ self.slas: Resource[Dict[str, Any]] = Resource(t, "/slas")
79
+ self.triggers: Resource[Dict[str, Any]] = Resource(t, "/triggers")
80
+ self.jobs: Resource[Dict[str, Any]] = Resource(t, "/jobs")
81
+ self.webhooks: Resource[Dict[str, Any]] = Resource(t, "/webhooks")
82
+ self.calendars: Resource[Dict[str, Any]] = Resource(t, "/calendars")
83
+ self.object_manager_attributes: Resource[Dict[str, Any]] = Resource(t, "/object_manager_attributes")
84
+ self.online_notifications: Resource[Dict[str, Any]] = Resource(t, "/online_notifications")
85
+ self.user_access_tokens: Resource[Dict[str, Any]] = Resource(t, "/user_access_token")
86
+ self.checklist_templates: Resource[Dict[str, Any]] = Resource(t, "/checklist_templates")
87
+ # Everything
88
+ self.api = Api(t)
89
+
90
+ def version(self) -> str:
91
+ """The instance's Zammad version (``/version``)."""
92
+ result = self.api.version.index()
93
+ return str(result.get("version", "")) if isinstance(result, dict) else str(result)
94
+
95
+ def __repr__(self) -> str:
96
+ return f"<ZammadClient {self.transport.base_url}>"
97
+
98
+
99
+ __all__ = ["ZammadClient"]
@@ -0,0 +1,50 @@
1
+ """Exception hierarchy for the Zammad client."""
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class ZammadError(Exception):
7
+ """Base exception for all Zammad API errors.
8
+
9
+ Transport failures (connection errors, timeouts) are wrapped in this
10
+ exception as well, so catching it covers everything the client raises.
11
+ """
12
+
13
+
14
+ class ZammadAuthError(ZammadError):
15
+ """Raised when authentication fails (HTTP 401) or credentials are missing."""
16
+
17
+
18
+ class ZammadPermissionError(ZammadError):
19
+ """Raised when the token lacks a permission for the call (HTTP 403).
20
+
21
+ Zammad is explicit about this, e.g. a token without ``ticket.agent`` reading
22
+ tickets, or ``knowledge_base.reader`` missing for the knowledge base.
23
+ """
24
+
25
+
26
+ class ZammadNotFoundError(ZammadError):
27
+ """Raised when the record does not exist or is not visible (HTTP 404).
28
+
29
+ Zammad answers 404 for both cases, so "not found" may mean "not yours".
30
+ """
31
+
32
+
33
+ class ZammadRateLimitError(ZammadError):
34
+ """Raised when a rate limit (HTTP 429) could not be resolved automatically.
35
+
36
+ ``retry_after`` carries the seconds Zammad asked to wait, when it said so.
37
+ """
38
+
39
+ def __init__(self, message: str, retry_after: Optional[int] = None) -> None:
40
+ super().__init__(message)
41
+ self.retry_after = retry_after
42
+
43
+
44
+ __all__ = [
45
+ "ZammadError",
46
+ "ZammadAuthError",
47
+ "ZammadPermissionError",
48
+ "ZammadNotFoundError",
49
+ "ZammadRateLimitError",
50
+ ]
File without changes
@@ -0,0 +1,22 @@
1
+ from .base import Endpoint, Resource
2
+ from .generated import Api
3
+ from .knowledge_base import KnowledgeBase
4
+ from .people import Groups, Organizations, Roles, TicketPriorities, TicketStates, Users
5
+ from .tickets import Tags, TicketArticles, TimeAccountings, Tickets
6
+
7
+ __all__ = [
8
+ "Endpoint",
9
+ "Resource",
10
+ "Api",
11
+ "KnowledgeBase",
12
+ "Tickets",
13
+ "TicketArticles",
14
+ "Tags",
15
+ "TimeAccountings",
16
+ "Users",
17
+ "Organizations",
18
+ "Groups",
19
+ "Roles",
20
+ "TicketStates",
21
+ "TicketPriorities",
22
+ ]
@@ -0,0 +1,114 @@
1
+ """Base classes shared by generated and hand-written resources.
2
+
3
+ ``Endpoint`` is the thinnest possible layer over :class:`Transport`: it turns a
4
+ route template plus path parameters into one call. The generated module builds
5
+ one method per Zammad route on it. ``Resource`` adds the CRUD conveniences that
6
+ most Zammad collections share (``/things``, ``/things/:id``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, Generic, Iterator, List, Mapping, Optional, TypeVar, cast
12
+
13
+ from ..transport import DEFAULT_PER_PAGE, Transport
14
+
15
+ T = TypeVar("T", bound=Mapping[str, Any])
16
+
17
+ Params = Optional[Mapping[str, Any]]
18
+ Json = Optional[Mapping[str, Any]]
19
+
20
+
21
+ class Endpoint:
22
+ """A group of routes sharing one Zammad controller."""
23
+
24
+ controller: str = ""
25
+
26
+ def __init__(self, transport: Transport) -> None:
27
+ self._transport = transport
28
+
29
+ @staticmethod
30
+ def _fill(template: str, **path_params: Any) -> str:
31
+ """Substitutes ``:name`` segments; values are stringified as-is."""
32
+ path = template
33
+ for name, value in path_params.items():
34
+ path = path.replace(f":{name}", str(value))
35
+ if ":" in path.split("?")[0]:
36
+ raise ValueError(f"unfilled path parameter in {path!r}")
37
+ return path.lstrip("/")
38
+
39
+ def _call(
40
+ self,
41
+ method: str,
42
+ template: str,
43
+ path_params: Mapping[str, Any],
44
+ params: Params = None,
45
+ json: Json = None,
46
+ on_behalf_of: Optional[str] = None,
47
+ raw: bool = False,
48
+ ) -> Any:
49
+ return self._transport.request(
50
+ method,
51
+ self._fill(template, **path_params),
52
+ params=dict(params) if params else None,
53
+ json=dict(json) if json is not None else None,
54
+ on_behalf_of=on_behalf_of,
55
+ raw=raw,
56
+ )
57
+
58
+ def __repr__(self) -> str:
59
+ return f"<{type(self).__name__} controller={self.controller!r}>"
60
+
61
+
62
+ class Resource(Endpoint, Generic[T]):
63
+ """CRUD over a standard Zammad collection.
64
+
65
+ ``path`` is the collection path relative to ``/api/v1`` (``/users``). Most
66
+ collections also support ``?expand=true`` to inline relations and
67
+ ``page``/``per_page`` for paging; both are plain query parameters here.
68
+ """
69
+
70
+ path: str = ""
71
+
72
+ def __init__(self, transport: Transport, path: Optional[str] = None) -> None:
73
+ super().__init__(transport)
74
+ if path is not None:
75
+ self.path = path
76
+ if not self.path:
77
+ raise ValueError(f"{type(self).__name__} needs a collection path")
78
+
79
+ def list(self, *, expand: bool = False, on_behalf_of: Optional[str] = None, **params: Any) -> List[T]:
80
+ """One page of records (``page``/``per_page`` as keyword arguments)."""
81
+ if expand:
82
+ params["expand"] = "true"
83
+ result = self._transport.get(self.path.lstrip("/"), params=params or None, on_behalf_of=on_behalf_of)
84
+ return cast(List[T], list(result) if isinstance(result, list) else [])
85
+
86
+ def iter_all(
87
+ self, *, expand: bool = False, per_page: int = DEFAULT_PER_PAGE, on_behalf_of: Optional[str] = None, **params: Any
88
+ ) -> Iterator[T]:
89
+ """Every record, fetching pages lazily."""
90
+ if expand:
91
+ params["expand"] = "true"
92
+ return cast(
93
+ Iterator[T],
94
+ self._transport.paginate(self.path.lstrip("/"), params=params or None, per_page=per_page, on_behalf_of=on_behalf_of),
95
+ )
96
+
97
+ def list_all(self, **kwargs: Any) -> List[T]:
98
+ return list(self.iter_all(**kwargs))
99
+
100
+ def get(self, record_id: int, *, expand: bool = False, on_behalf_of: Optional[str] = None) -> T:
101
+ params = {"expand": "true"} if expand else None
102
+ return cast(T, self._transport.get(f"{self.path.lstrip('/')}/{record_id}", params=params, on_behalf_of=on_behalf_of))
103
+
104
+ def create(self, data: Mapping[str, Any], *, on_behalf_of: Optional[str] = None) -> T:
105
+ return cast(T, self._transport.post(self.path.lstrip("/"), json=dict(data), on_behalf_of=on_behalf_of))
106
+
107
+ def update(self, record_id: int, data: Mapping[str, Any], *, on_behalf_of: Optional[str] = None) -> T:
108
+ return cast(T, self._transport.put(f"{self.path.lstrip('/')}/{record_id}", json=dict(data), on_behalf_of=on_behalf_of))
109
+
110
+ def delete(self, record_id: int, *, on_behalf_of: Optional[str] = None) -> None:
111
+ self._transport.delete(f"{self.path.lstrip('/')}/{record_id}", on_behalf_of=on_behalf_of)
112
+
113
+
114
+ __all__ = ["Endpoint", "Resource", "Params", "Json"]