simpro-py-sdk 0.1.0__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.
@@ -0,0 +1,24 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.12", "3.13", "3.14"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: astral-sh/setup-uv@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - run: uv sync --frozen
21
+ - run: uv run ruff check .
22
+ - run: uv run ruff format --check .
23
+ - run: uv run mypy
24
+ - run: uv run pytest -q
@@ -0,0 +1,20 @@
1
+ name: Publish
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ environment: pypi
11
+ permissions:
12
+ # PyPI trusted publishing (OIDC).
13
+ id-token: write
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: astral-sh/setup-uv@v5
17
+ - run: uv sync --frozen
18
+ - run: uv run pytest -q
19
+ - run: uv build
20
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,11 @@
1
+ .idea/
2
+ .vscode/
3
+ dist/
4
+ build/
5
+ *.egg-info/
6
+ __pycache__/
7
+ *.pyc
8
+ .venv/
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2016 Bradley McElroy
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,171 @@
1
+ Metadata-Version: 2.5
2
+ Name: simpro-py-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for the SimPro Cloud REST API (v1.0).
5
+ Project-URL: Homepage, https://github.com/xuanpablo/simpro-py
6
+ Project-URL: Changelog, https://github.com/xuanpablo/simpro-py/releases
7
+ Author: Paul Millar
8
+ License: MIT License
9
+
10
+ Copyright (c) 2016 Bradley McElroy
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENCE.txt
30
+ Keywords: api,client,construction,simpro,simprosuite
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Programming Language :: Python :: 3.12
36
+ Classifier: Programming Language :: Python :: 3.13
37
+ Classifier: Programming Language :: Python :: 3.14
38
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
39
+ Requires-Python: >=3.12
40
+ Requires-Dist: httpx>=0.27
41
+ Description-Content-Type: text/markdown
42
+
43
+ # simpro-py
44
+
45
+ A thin Python client for the [SimPro Cloud REST API (v1.0)](https://www.simprogroup.com).
46
+
47
+ ```python
48
+ from simpro import SimproClient
49
+
50
+ client = SimproClient("https://yourtenant.simprosuite.com", "YOUR_API_KEY")
51
+
52
+ for customer in client.customers.iter_all(0):
53
+ print(customer["ID"], customer.get("CompanyName") or customer.get("FamilyName"))
54
+ ```
55
+
56
+ The distribution is `simpro-py-sdk`; the import name is `simpro`.
57
+
58
+ ## Install
59
+
60
+ ```bash
61
+ pip install simpro-py-sdk
62
+ ```
63
+
64
+ Requires Python 3.12+. The only runtime dependency is `httpx`.
65
+
66
+ ## Authentication
67
+
68
+ SimPro API keys are bearer tokens — create one in SimPro under
69
+ **Administration > API Keys** and pass it with your tenant base URL:
70
+
71
+ ```python
72
+ client = SimproClient("https://yourtenant.simprosuite.com", "YOUR_API_KEY")
73
+ ```
74
+
75
+ Every request is sent to `{base_url}/api/v1.0/...`. If your `base_url` already
76
+ ends with `/api/v1.0` it is stripped automatically, so the well-known
77
+ doubled-prefix 404 (`Invalid route`) cannot happen.
78
+
79
+ ## Resources
80
+
81
+ 0.1.x ships read-only access to the first-slice resources, one namespace per
82
+ resource, hung off the client:
83
+
84
+ | Namespace | Endpoints |
85
+ |---|---|
86
+ | `client.companies` | `list(*, search=None, modified_since=None, **filters)`, `get(company_id)` |
87
+ | `client.customers` | `list(company_id, ...)`, `get(company_id, customer_id)`, `iter_all(company_id, **filters)` |
88
+ | `client.sites` | `list(company_id, ...)`, `get(company_id, site_id)`, `iter_all(company_id, **filters)` |
89
+ | `client.jobs` | `list(company_id, ...)`, `get(company_id, job_id)`, `iter_all(company_id, **filters)` |
90
+
91
+ `company_id` is `0` unless your build uses SimPro multi-company.
92
+
93
+ Notes:
94
+
95
+ - **Single-customer GETs are type-split in SimPro** (company vs individual).
96
+ `client.customers.get(company_id, customer_id)` tries the company path first
97
+ and falls back to individuals, so callers never need the type up front.
98
+ - **`search`** is SimPro's documented match-mode param (`"all"`/`"any"`) that
99
+ combines with field filters. Field filters themselves are passed verbatim as
100
+ extra keyword arguments, e.g. `client.customers.list(0, Name="Acme")`.
101
+ - All methods return plain dicts/lists — no DTO layer by design.
102
+
103
+ ## Pagination
104
+
105
+ `list()` fetches a single page (`page`, `per_page`, capped at SimPro's maximum
106
+ of 250). `iter_all()` walks every page for you:
107
+
108
+ ```python
109
+ for job in client.jobs.iter_all(0):
110
+ ...
111
+ ```
112
+
113
+ Page continuation follows the SimPro convention: the `Result-Pages` response
114
+ header carries the total page count; if it is absent, the walk stops on a
115
+ short page.
116
+
117
+ ## Incremental pulls
118
+
119
+ List endpoints honour the `If-Modified-Since` watermark. Pass
120
+ `modified_since=<datetime>` and the client formats the header (RFC 1123, UTC)
121
+ and maps a `304 Not Modified` answer to an empty result:
122
+
123
+ ```python
124
+ since = last_sync_run_at # aware datetime; naive values are treated as UTC
125
+ new_customers = client.customers.list(0, modified_since=since)
126
+ ```
127
+
128
+ ## Errors
129
+
130
+ All failures raise a subclass of `SimproError`:
131
+
132
+ | Exception | HTTP status |
133
+ |---|---|
134
+ | `SimproAuthError` | 401, 403 |
135
+ | `SimproNotFound` | 404 |
136
+ | `SimproValidationError` | 422 (`.details` holds the raw error list) |
137
+ | `SimproRateLimitError` | 429 |
138
+ | `SimproError` | anything else, including transport failures |
139
+
140
+ SimPro 422 bodies are normally `{"errors": [{"path", "message", "value"}, ...]}`
141
+ but the `errors` key may be absent — both shapes are handled, and
142
+ `SimproValidationError.details` is always a list.
143
+
144
+ ## Deliberate omissions
145
+
146
+ - **No retry, no rate limiting, no caching.** SimPro allows roughly 10
147
+ requests/second per key; callers doing bulk pulls should pace requests and
148
+ retry 429s/transport errors themselves.
149
+ - **No write endpoints** in 0.1.x — read-only first.
150
+ - **No DTO layer** — responses are plain JSON dicts, so SDK releases never
151
+ lag the API.
152
+
153
+ ## Lineage
154
+
155
+ This package is a clean rewrite of [`limx0/simpro-py`](https://github.com/limx0/simpro-py)
156
+ (MIT), which wrapped SimPro's legacy on-prem JSON-RPC API. The rewrite targets
157
+ the SimPro Cloud REST API and shares no code with the original; the MIT
158
+ licence and lineage are retained with thanks.
159
+
160
+ ## Development
161
+
162
+ ```bash
163
+ uv sync
164
+ uv run pytest -q
165
+ uv run ruff check . && uv run ruff format --check .
166
+ uv run mypy
167
+ ```
168
+
169
+ ## Licence
170
+
171
+ MIT — see [LICENCE.txt](LICENCE.txt).
@@ -0,0 +1,129 @@
1
+ # simpro-py
2
+
3
+ A thin Python client for the [SimPro Cloud REST API (v1.0)](https://www.simprogroup.com).
4
+
5
+ ```python
6
+ from simpro import SimproClient
7
+
8
+ client = SimproClient("https://yourtenant.simprosuite.com", "YOUR_API_KEY")
9
+
10
+ for customer in client.customers.iter_all(0):
11
+ print(customer["ID"], customer.get("CompanyName") or customer.get("FamilyName"))
12
+ ```
13
+
14
+ The distribution is `simpro-py-sdk`; the import name is `simpro`.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install simpro-py-sdk
20
+ ```
21
+
22
+ Requires Python 3.12+. The only runtime dependency is `httpx`.
23
+
24
+ ## Authentication
25
+
26
+ SimPro API keys are bearer tokens — create one in SimPro under
27
+ **Administration > API Keys** and pass it with your tenant base URL:
28
+
29
+ ```python
30
+ client = SimproClient("https://yourtenant.simprosuite.com", "YOUR_API_KEY")
31
+ ```
32
+
33
+ Every request is sent to `{base_url}/api/v1.0/...`. If your `base_url` already
34
+ ends with `/api/v1.0` it is stripped automatically, so the well-known
35
+ doubled-prefix 404 (`Invalid route`) cannot happen.
36
+
37
+ ## Resources
38
+
39
+ 0.1.x ships read-only access to the first-slice resources, one namespace per
40
+ resource, hung off the client:
41
+
42
+ | Namespace | Endpoints |
43
+ |---|---|
44
+ | `client.companies` | `list(*, search=None, modified_since=None, **filters)`, `get(company_id)` |
45
+ | `client.customers` | `list(company_id, ...)`, `get(company_id, customer_id)`, `iter_all(company_id, **filters)` |
46
+ | `client.sites` | `list(company_id, ...)`, `get(company_id, site_id)`, `iter_all(company_id, **filters)` |
47
+ | `client.jobs` | `list(company_id, ...)`, `get(company_id, job_id)`, `iter_all(company_id, **filters)` |
48
+
49
+ `company_id` is `0` unless your build uses SimPro multi-company.
50
+
51
+ Notes:
52
+
53
+ - **Single-customer GETs are type-split in SimPro** (company vs individual).
54
+ `client.customers.get(company_id, customer_id)` tries the company path first
55
+ and falls back to individuals, so callers never need the type up front.
56
+ - **`search`** is SimPro's documented match-mode param (`"all"`/`"any"`) that
57
+ combines with field filters. Field filters themselves are passed verbatim as
58
+ extra keyword arguments, e.g. `client.customers.list(0, Name="Acme")`.
59
+ - All methods return plain dicts/lists — no DTO layer by design.
60
+
61
+ ## Pagination
62
+
63
+ `list()` fetches a single page (`page`, `per_page`, capped at SimPro's maximum
64
+ of 250). `iter_all()` walks every page for you:
65
+
66
+ ```python
67
+ for job in client.jobs.iter_all(0):
68
+ ...
69
+ ```
70
+
71
+ Page continuation follows the SimPro convention: the `Result-Pages` response
72
+ header carries the total page count; if it is absent, the walk stops on a
73
+ short page.
74
+
75
+ ## Incremental pulls
76
+
77
+ List endpoints honour the `If-Modified-Since` watermark. Pass
78
+ `modified_since=<datetime>` and the client formats the header (RFC 1123, UTC)
79
+ and maps a `304 Not Modified` answer to an empty result:
80
+
81
+ ```python
82
+ since = last_sync_run_at # aware datetime; naive values are treated as UTC
83
+ new_customers = client.customers.list(0, modified_since=since)
84
+ ```
85
+
86
+ ## Errors
87
+
88
+ All failures raise a subclass of `SimproError`:
89
+
90
+ | Exception | HTTP status |
91
+ |---|---|
92
+ | `SimproAuthError` | 401, 403 |
93
+ | `SimproNotFound` | 404 |
94
+ | `SimproValidationError` | 422 (`.details` holds the raw error list) |
95
+ | `SimproRateLimitError` | 429 |
96
+ | `SimproError` | anything else, including transport failures |
97
+
98
+ SimPro 422 bodies are normally `{"errors": [{"path", "message", "value"}, ...]}`
99
+ but the `errors` key may be absent — both shapes are handled, and
100
+ `SimproValidationError.details` is always a list.
101
+
102
+ ## Deliberate omissions
103
+
104
+ - **No retry, no rate limiting, no caching.** SimPro allows roughly 10
105
+ requests/second per key; callers doing bulk pulls should pace requests and
106
+ retry 429s/transport errors themselves.
107
+ - **No write endpoints** in 0.1.x — read-only first.
108
+ - **No DTO layer** — responses are plain JSON dicts, so SDK releases never
109
+ lag the API.
110
+
111
+ ## Lineage
112
+
113
+ This package is a clean rewrite of [`limx0/simpro-py`](https://github.com/limx0/simpro-py)
114
+ (MIT), which wrapped SimPro's legacy on-prem JSON-RPC API. The rewrite targets
115
+ the SimPro Cloud REST API and shares no code with the original; the MIT
116
+ licence and lineage are retained with thanks.
117
+
118
+ ## Development
119
+
120
+ ```bash
121
+ uv sync
122
+ uv run pytest -q
123
+ uv run ruff check . && uv run ruff format --check .
124
+ uv run mypy
125
+ ```
126
+
127
+ ## Licence
128
+
129
+ MIT — see [LICENCE.txt](LICENCE.txt).
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "simpro-py-sdk"
3
+ version = "0.1.0"
4
+ description = "Python client for the SimPro Cloud REST API (v1.0)."
5
+ readme = "README.md"
6
+ license = { file = "LICENCE.txt" }
7
+ requires-python = ">=3.12"
8
+ authors = [{ name = "Paul Millar" }]
9
+ keywords = ["simpro", "simprosuite", "construction", "api", "client"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Programming Language :: Python :: 3.14",
18
+ "Topic :: Software Development :: Libraries :: Python Modules",
19
+ ]
20
+ dependencies = ["httpx>=0.27"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/xuanpablo/simpro-py"
24
+ Changelog = "https://github.com/xuanpablo/simpro-py/releases"
25
+
26
+ [build-system]
27
+ requires = ["hatchling"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [dependency-groups]
31
+ dev = ["pytest>=8", "ruff==0.16.9", "mypy==2.3.1"]
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/simpro"]
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+ target-version = "py312"
42
+ src = ["src", "tests"]
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "F", "W", "I", "UP", "B", "SIM"]
46
+
47
+ [tool.mypy]
48
+ python_version = "3.12"
49
+ files = ["src/simpro"]
@@ -0,0 +1,31 @@
1
+ """simpro-py: a thin Python client for the SimPro Cloud REST API (v1.0).
2
+
3
+ Quickstart::
4
+
5
+ from simpro import SimproClient
6
+
7
+ client = SimproClient("https://yourtenant.simprosuite.com", "API_KEY")
8
+ for customer in client.customers.iter_all(0):
9
+ print(customer["ID"], customer.get("CompanyName"))
10
+ """
11
+
12
+ from simpro.client import SimproClient
13
+ from simpro.exceptions import (
14
+ SimproAuthError,
15
+ SimproError,
16
+ SimproNotFound,
17
+ SimproRateLimitError,
18
+ SimproValidationError,
19
+ )
20
+
21
+ __version__ = "0.1.0"
22
+
23
+ __all__ = [
24
+ "SimproAuthError",
25
+ "SimproClient",
26
+ "SimproError",
27
+ "SimproNotFound",
28
+ "SimproRateLimitError",
29
+ "SimproValidationError",
30
+ "__version__",
31
+ ]
@@ -0,0 +1,19 @@
1
+ """Internal helpers shared by the client and the resource modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+ from email.utils import format_datetime
7
+
8
+ API_PREFIX = "/api/v1.0"
9
+ MAX_PAGE_SIZE = 250
10
+
11
+
12
+ def format_http_date(dt: datetime) -> str:
13
+ """Format ``dt`` as an RFC 1123 date string (UTC), for ``If-Modified-Since``.
14
+
15
+ Naive datetimes are treated as UTC.
16
+ """
17
+ if dt.tzinfo is None:
18
+ dt = dt.replace(tzinfo=UTC)
19
+ return format_datetime(dt.astimezone(UTC), usegmt=True)
@@ -0,0 +1,152 @@
1
+ """The SimPro Cloud REST API client.
2
+
3
+ Every request URL is built in one place (``_request``) as
4
+ ``{base}/api/v1.0{path}``; if ``base_url`` already ends with ``/api/v1.0``
5
+ the prefix is stripped first, so the well-known doubling trap (simPRO
6
+ answers 404 ``Invalid route``) is impossible by construction.
7
+
8
+ The client is intentionally thin: no retry, no rate limiting, no caching.
9
+ SimPro allows roughly 10 requests/second per key — callers with bulk pulls
10
+ should pace requests and retry 429s/transport errors themselves.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Mapping
16
+ from typing import Any, Self
17
+
18
+ import httpx
19
+
20
+ from simpro._util import API_PREFIX
21
+ from simpro.exceptions import (
22
+ SimproAuthError,
23
+ SimproError,
24
+ SimproNotFound,
25
+ SimproRateLimitError,
26
+ SimproValidationError,
27
+ )
28
+ from simpro.resources import Companies, Customers, Jobs, Sites
29
+
30
+ DEFAULT_TIMEOUT = 30.0
31
+
32
+
33
+ class SimproClient:
34
+ """Synchronous client for the SimPro Cloud REST API (v1.0).
35
+
36
+ Args:
37
+ base_url: Tenant root, e.g. ``https://yourtenant.simprosuite.com``.
38
+ A trailing ``/api/v1.0`` is tolerated and stripped.
39
+ api_key: API key bearer token (SimPro > Administration > API Keys).
40
+ timeout: Per-request timeout in seconds.
41
+ transport: Optional ``httpx`` transport override (testing/proxies).
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ base_url: str,
47
+ api_key: str,
48
+ *,
49
+ timeout: float = DEFAULT_TIMEOUT,
50
+ transport: httpx.BaseTransport | None = None,
51
+ ) -> None:
52
+ base = base_url.rstrip("/").removesuffix(API_PREFIX)
53
+ self._base = base
54
+ self._http = httpx.Client(
55
+ timeout=timeout,
56
+ headers={
57
+ "Authorization": f"Bearer {api_key}",
58
+ "Accept": "application/json",
59
+ },
60
+ transport=transport,
61
+ )
62
+ # Resource namespaces.
63
+ self.companies = Companies(self)
64
+ self.customers = Customers(self)
65
+ self.sites = Sites(self)
66
+ self.jobs = Jobs(self)
67
+
68
+ def __enter__(self) -> Self:
69
+ return self
70
+
71
+ def __exit__(self, *exc_info: object) -> None:
72
+ self.close()
73
+
74
+ def close(self) -> None:
75
+ """Close the underlying connection pool."""
76
+ self._http.close()
77
+
78
+ def _request(
79
+ self,
80
+ method: str,
81
+ path: str,
82
+ *,
83
+ params: Mapping[str, Any] | None = None,
84
+ headers: Mapping[str, str] | None = None,
85
+ ) -> httpx.Response:
86
+ """Perform one API request and map failures to typed exceptions.
87
+
88
+ ``path`` is relative to the API prefix and starts with ``/``,
89
+ e.g. ``/companies/0/customers/``. A 304 (If-Modified-Since hit) is
90
+ returned to the caller as a normal response.
91
+ """
92
+ url = f"{self._base}{API_PREFIX}{path}"
93
+ try:
94
+ response = self._http.request(method, url, params=params, headers=headers)
95
+ except httpx.HTTPError as exc:
96
+ raise SimproError(f"SimPro request failed: {exc}") from exc
97
+ _raise_for_status(response)
98
+ return response
99
+
100
+
101
+ def _raise_for_status(response: httpx.Response) -> None:
102
+ status = response.status_code
103
+ if status < 400 or status == 304:
104
+ return
105
+ if status in (401, 403):
106
+ raise SimproAuthError(
107
+ f"SimPro rejected the credentials (HTTP {status})", status_code=status
108
+ )
109
+ if status == 404:
110
+ raise SimproNotFound(f"SimPro resource not found: {response.url}", status_code=status)
111
+ if status == 429:
112
+ raise SimproRateLimitError(
113
+ "SimPro rate limit exceeded; retry after a pause", status_code=status
114
+ )
115
+ if status == 422:
116
+ message, details = _parse_validation_body(response)
117
+ raise SimproValidationError(message, details=details, status_code=status)
118
+ raise SimproError(
119
+ f"SimPro request failed with HTTP {status}: {response.text[:200]}",
120
+ status_code=status,
121
+ )
122
+
123
+
124
+ def _parse_validation_body(
125
+ response: httpx.Response,
126
+ ) -> tuple[str, list[dict[str, Any]]]:
127
+ """Extract a message and error details from a 422 body.
128
+
129
+ SimPro 422 bodies are ``{"errors": [{"path", "message", "value"}, ...]}``
130
+ — but the ``errors`` key may be absent, and the body may not be JSON at
131
+ all. Both shapes degrade gracefully.
132
+ """
133
+ try:
134
+ body: Any = response.json()
135
+ except ValueError:
136
+ body = None
137
+ if isinstance(body, dict):
138
+ errors = body.get("errors")
139
+ details = [e for e in errors if isinstance(e, dict)] if isinstance(errors, list) else []
140
+ message = body.get("message") if isinstance(body.get("message"), str) else None
141
+ if message is None:
142
+ message = "SimPro rejected the request payload (HTTP 422)"
143
+ if details:
144
+ summary = "; ".join(
145
+ f"{d.get('path', '?')}: {d.get('message', '')}" for d in details[:5]
146
+ )
147
+ message = f"{message} — {summary}"
148
+ return message, details
149
+ if isinstance(body, list):
150
+ details = [e for e in body if isinstance(e, dict)]
151
+ return "SimPro rejected the request payload (HTTP 422)", details
152
+ return f"SimPro rejected the request payload (HTTP 422): {response.text[:200]}", []
@@ -0,0 +1,49 @@
1
+ """Exception hierarchy for the simpro client.
2
+
3
+ Every HTTP failure is mapped to one of these types in one place
4
+ (``simpro.client``); transport-level failures raise ``SimproError``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+
12
+ class SimproError(Exception):
13
+ """Base error for all simpro failures (transport or HTTP)."""
14
+
15
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
16
+ super().__init__(message)
17
+ self.status_code = status_code
18
+
19
+
20
+ class SimproAuthError(SimproError):
21
+ """SimPro rejected the request as unauthenticated or unauthorised (401/403)."""
22
+
23
+
24
+ class SimproNotFound(SimproError):
25
+ """The requested SimPro resource does not exist (404)."""
26
+
27
+
28
+ class SimproRateLimitError(SimproError):
29
+ """SimPro rate limit exceeded (429). Retry after a pause; the SDK does not retry."""
30
+
31
+
32
+ class SimproValidationError(SimproError):
33
+ """SimPro rejected the request payload (422).
34
+
35
+ ``details`` carries the raw error list when the response body provides
36
+ one: SimPro returns ``{"errors": [{"path", "message", "value"}, ...]}``
37
+ but the ``errors`` key may be absent, in which case ``details`` is empty
38
+ and the message carries whatever the body offered.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ message: str,
44
+ *,
45
+ details: list[dict[str, Any]] | None = None,
46
+ status_code: int | None = None,
47
+ ) -> None:
48
+ super().__init__(message, status_code=status_code)
49
+ self.details = details if details is not None else []