templr 0.1.0__py3-none-any.whl

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.
templr/__init__.py ADDED
@@ -0,0 +1,82 @@
1
+ """Official Python SDK for the Templr REST API.
2
+
3
+ Example:
4
+ >>> from templr import Templr
5
+ >>> client = Templr(api_key="tmpl_...", base_url="https://templr.example.com")
6
+ >>> email = client.templates.render("8f0c...", values={"name": "Ada"})
7
+ >>> email.html
8
+ """
9
+
10
+ from importlib.metadata import version
11
+
12
+ from ._client import AsyncTemplr, Templr
13
+ from .errors import (
14
+ APIConnectionError,
15
+ APIError,
16
+ APITimeoutError,
17
+ AuthenticationError,
18
+ BadRequestError,
19
+ ConflictError,
20
+ InternalServerError,
21
+ NotFoundError,
22
+ PayloadTooLargeError,
23
+ PermissionDeniedError,
24
+ RateLimitError,
25
+ TemplrError,
26
+ UnexpectedResponseError,
27
+ UploadError,
28
+ )
29
+ from .models import (
30
+ Asset,
31
+ AssetUpload,
32
+ Deleted,
33
+ ImageContentType,
34
+ Page,
35
+ PresignedUpload,
36
+ RenderedTemplate,
37
+ Template,
38
+ TemplateDocument,
39
+ TemplateMark,
40
+ TemplateNode,
41
+ TemplateSummary,
42
+ TemplateVariable,
43
+ TemplateVersion,
44
+ TemplateVersionSummary,
45
+ )
46
+
47
+ __version__ = version("templr")
48
+
49
+ __all__ = [
50
+ "APIConnectionError",
51
+ "APIError",
52
+ "APITimeoutError",
53
+ "Asset",
54
+ "AssetUpload",
55
+ "AsyncTemplr",
56
+ "AuthenticationError",
57
+ "BadRequestError",
58
+ "ConflictError",
59
+ "Deleted",
60
+ "ImageContentType",
61
+ "InternalServerError",
62
+ "NotFoundError",
63
+ "Page",
64
+ "PayloadTooLargeError",
65
+ "PermissionDeniedError",
66
+ "PresignedUpload",
67
+ "RateLimitError",
68
+ "RenderedTemplate",
69
+ "Template",
70
+ "TemplateDocument",
71
+ "TemplateMark",
72
+ "TemplateNode",
73
+ "TemplateSummary",
74
+ "TemplateVariable",
75
+ "TemplateVersion",
76
+ "TemplateVersionSummary",
77
+ "Templr",
78
+ "TemplrError",
79
+ "UnexpectedResponseError",
80
+ "UploadError",
81
+ "__version__",
82
+ ]
templr/_client.py ADDED
@@ -0,0 +1,134 @@
1
+ """The sync and async Templr clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import TracebackType
6
+
7
+ import httpx
8
+ from pydantic import JsonValue, TypeAdapter
9
+
10
+ from ._transport import DEFAULT_TIMEOUT, ApiRequest, AsyncTransport, SyncTransport
11
+ from .resources import Assets, AsyncAssets, AsyncTemplates, Templates
12
+
13
+ _DOCUMENT = TypeAdapter(dict[str, JsonValue])
14
+ _OPENAPI_DOCUMENT = ApiRequest("GET", "/api/v1/openapi.json")
15
+
16
+
17
+ class Templr:
18
+ """Client of the Templr REST API v1.
19
+
20
+ Every request is scoped to the workspace of the API key. Use it as a
21
+ context manager, or call :meth:`close` when done, to release connections.
22
+
23
+ Example:
24
+ >>> from templr import Templr
25
+ >>> with Templr(api_key="tmpl_...", base_url="https://templr.example.com") as client:
26
+ ... email = client.templates.render("8f0c...", values={"name": "Ada"})
27
+
28
+ Attributes:
29
+ templates: List, get and render templates.
30
+ assets: Upload, list and delete images.
31
+ """
32
+
33
+ templates: Templates
34
+ assets: Assets
35
+
36
+ def __init__(
37
+ self,
38
+ *,
39
+ api_key: str,
40
+ base_url: str,
41
+ timeout: float = DEFAULT_TIMEOUT,
42
+ http_client: httpx.Client | None = None,
43
+ ) -> None:
44
+ """Creates a client.
45
+
46
+ Args:
47
+ api_key: A workspace API key. Keep it secret: never ship it to a browser or mobile app.
48
+ base_url: The URL of your Templr instance, e.g. ``https://templr.example.com``.
49
+ timeout: Seconds to wait for each request.
50
+ http_client: An ``httpx.Client`` to send requests with (proxies, custom TLS...).
51
+ The SDK does not close a client it did not create.
52
+
53
+ Raises:
54
+ ValueError: ``api_key`` is empty or ``base_url`` is not an http(s) URL.
55
+ """
56
+ self._transport = SyncTransport(api_key=api_key, base_url=base_url, timeout=timeout, http_client=http_client)
57
+ self.templates = Templates(self._transport)
58
+ self.assets = Assets(self._transport)
59
+
60
+ def get_openapi_document(self) -> dict[str, JsonValue]:
61
+ """Gets the OpenAPI 3.1 document of the API served by this instance."""
62
+ return self._transport.send(_OPENAPI_DOCUMENT, _DOCUMENT)
63
+
64
+ def close(self) -> None:
65
+ """Releases the connections of the client."""
66
+ self._transport.close()
67
+
68
+ def __enter__(self) -> Templr:
69
+ """Returns the client."""
70
+ return self
71
+
72
+ def __exit__(
73
+ self,
74
+ exc_type: type[BaseException] | None,
75
+ exc: BaseException | None,
76
+ traceback: TracebackType | None,
77
+ ) -> None:
78
+ """Closes the client."""
79
+ self.close()
80
+
81
+
82
+ class AsyncTemplr:
83
+ """Async client of the Templr REST API v1; see :class:`Templr`.
84
+
85
+ Example:
86
+ >>> from templr import AsyncTemplr
87
+ >>> async with AsyncTemplr(api_key="tmpl_...", base_url="https://templr.example.com") as client:
88
+ ... email = await client.templates.render("8f0c...", values={"name": "Ada"})
89
+
90
+ Attributes:
91
+ templates: List, get and render templates.
92
+ assets: Upload, list and delete images.
93
+ """
94
+
95
+ templates: AsyncTemplates
96
+ assets: AsyncAssets
97
+
98
+ def __init__(
99
+ self,
100
+ *,
101
+ api_key: str,
102
+ base_url: str,
103
+ timeout: float = DEFAULT_TIMEOUT,
104
+ http_client: httpx.AsyncClient | None = None,
105
+ ) -> None:
106
+ """Creates a client; see :class:`Templr` for the arguments.
107
+
108
+ Raises:
109
+ ValueError: ``api_key`` is empty or ``base_url`` is not an http(s) URL.
110
+ """
111
+ self._transport = AsyncTransport(api_key=api_key, base_url=base_url, timeout=timeout, http_client=http_client)
112
+ self.templates = AsyncTemplates(self._transport)
113
+ self.assets = AsyncAssets(self._transport)
114
+
115
+ async def get_openapi_document(self) -> dict[str, JsonValue]:
116
+ """Gets the OpenAPI 3.1 document of the API served by this instance."""
117
+ return await self._transport.send(_OPENAPI_DOCUMENT, _DOCUMENT)
118
+
119
+ async def close(self) -> None:
120
+ """Releases the connections of the client."""
121
+ await self._transport.close()
122
+
123
+ async def __aenter__(self) -> AsyncTemplr:
124
+ """Returns the client."""
125
+ return self
126
+
127
+ async def __aexit__(
128
+ self,
129
+ exc_type: type[BaseException] | None,
130
+ exc: BaseException | None,
131
+ traceback: TracebackType | None,
132
+ ) -> None:
133
+ """Closes the client."""
134
+ await self.close()
templr/_transport.py ADDED
@@ -0,0 +1,268 @@
1
+ """HTTP plumbing shared by the sync and async clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass, field
7
+ from importlib.metadata import version
8
+ from typing import TypeVar
9
+ from urllib.parse import quote, urlsplit
10
+ from uuid import UUID
11
+
12
+ import httpx
13
+ from pydantic import BaseModel, JsonValue, TypeAdapter, ValidationError
14
+
15
+ from .errors import (
16
+ APIConnectionError,
17
+ APIError,
18
+ APITimeoutError,
19
+ AuthenticationError,
20
+ BadRequestError,
21
+ ConflictError,
22
+ InternalServerError,
23
+ NotFoundError,
24
+ PayloadTooLargeError,
25
+ PermissionDeniedError,
26
+ RateLimitError,
27
+ UnexpectedResponseError,
28
+ UploadError,
29
+ )
30
+
31
+ T = TypeVar("T")
32
+
33
+ API_KEY_HEADER = "x-api-key"
34
+ """The header that carries the workspace API key."""
35
+
36
+ DEFAULT_TIMEOUT = 30.0
37
+ """Seconds to wait for the API before raising :class:`~templr.errors.APITimeoutError`."""
38
+
39
+ USER_AGENT = f"templr-python/{version('templr')}"
40
+
41
+ QueryValue = str | int
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class FileUpload:
46
+ """A file sent to a presigned storage form, outside the API."""
47
+
48
+ url: str
49
+ fields: Mapping[str, str]
50
+ content: bytes
51
+ content_type: str
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class ApiRequest:
56
+ """One call to the API, independent of the sync or async client."""
57
+
58
+ method: str
59
+ path: str
60
+ params: Mapping[str, QueryValue] = field(default_factory=dict)
61
+ json: JsonValue = None
62
+
63
+
64
+ def path_id(value: str | UUID) -> str:
65
+ """Formats an id for a URL path, escaping anything that is not a plain path segment."""
66
+ return quote(str(value), safe="")
67
+
68
+
69
+ def query(**params: QueryValue | None) -> dict[str, QueryValue]:
70
+ """Drops the parameters that were not given."""
71
+ return {name: value for name, value in params.items() if value is not None}
72
+
73
+
74
+ def normalize_base_url(base_url: str) -> str:
75
+ """Validates the base URL of a Templr instance and strips its trailing slash.
76
+
77
+ Raises:
78
+ ValueError: The URL is not an absolute ``http`` or ``https`` URL.
79
+ """
80
+ parts = urlsplit(base_url)
81
+ if parts.scheme not in ("http", "https") or not parts.netloc:
82
+ msg = f"base_url must be an absolute http(s) URL, got {base_url!r}"
83
+ raise ValueError(msg)
84
+ return base_url.rstrip("/")
85
+
86
+
87
+ def validate_api_key(api_key: str) -> str:
88
+ """Rejects an empty API key.
89
+
90
+ Raises:
91
+ ValueError: The API key is empty.
92
+ """
93
+ if not api_key.strip():
94
+ msg = "api_key must not be empty"
95
+ raise ValueError(msg)
96
+ return api_key
97
+
98
+
99
+ class _ErrorDetail(BaseModel):
100
+ code: str
101
+ message: str
102
+ issues: list[str]
103
+
104
+
105
+ class _ErrorBody(BaseModel):
106
+ error: _ErrorDetail
107
+
108
+
109
+ _STATUS_ERRORS: Mapping[int, type[APIError]] = {
110
+ 400: BadRequestError,
111
+ 401: AuthenticationError,
112
+ 403: PermissionDeniedError,
113
+ 404: NotFoundError,
114
+ 409: ConflictError,
115
+ 413: PayloadTooLargeError,
116
+ 429: RateLimitError,
117
+ }
118
+
119
+
120
+ def _retry_after(response: httpx.Response) -> int | None:
121
+ value = response.headers.get("retry-after")
122
+ return int(value) if value is not None and value.isdigit() else None
123
+
124
+
125
+ def error_from_response(response: httpx.Response) -> APIError:
126
+ """Builds the :class:`~templr.errors.APIError` subclass that matches an error response."""
127
+ status = response.status_code
128
+ try:
129
+ detail = _ErrorBody.model_validate_json(response.content).error
130
+ code, message, issues = detail.code, detail.message, tuple(detail.issues)
131
+ except ValidationError:
132
+ code, message, issues = "unknown_error", f"HTTP {status} response without a Templr error body.", ()
133
+
134
+ error_class = _STATUS_ERRORS.get(status, InternalServerError if status >= 500 else APIError) # noqa: PLR2004
135
+ if error_class is RateLimitError:
136
+ return RateLimitError(message, status_code=status, code=code, issues=issues, retry_after=_retry_after(response))
137
+ return error_class(message, status_code=status, code=code, issues=issues)
138
+
139
+
140
+ def parse_response(response: httpx.Response, adapter: TypeAdapter[T]) -> T:
141
+ """Returns the typed body of a success response, or raises the matching error.
142
+
143
+ Raises:
144
+ APIError: The API answered with an error status.
145
+ UnexpectedResponseError: The body does not match the expected model.
146
+ """
147
+ if not response.is_success:
148
+ raise error_from_response(response)
149
+ try:
150
+ return adapter.validate_json(response.content)
151
+ except ValidationError as error:
152
+ raise UnexpectedResponseError(
153
+ f"The API response does not match the expected shape: {error}",
154
+ status_code=response.status_code,
155
+ body=response.text,
156
+ ) from error
157
+
158
+
159
+ def check_upload(response: httpx.Response) -> None:
160
+ """Raises :class:`~templr.errors.UploadError` when the bucket rejected the file."""
161
+ if not response.is_success:
162
+ raise UploadError(
163
+ f"The storage bucket rejected the file with HTTP {response.status_code}.",
164
+ status_code=response.status_code,
165
+ body=response.text,
166
+ )
167
+
168
+
169
+ class _BaseTransport:
170
+ def __init__(self, *, api_key: str, base_url: str, timeout: float) -> None:
171
+ self._base_url = normalize_base_url(base_url)
172
+ self._headers = {
173
+ API_KEY_HEADER: validate_api_key(api_key),
174
+ "accept": "application/json",
175
+ "user-agent": USER_AGENT,
176
+ }
177
+ self._timeout = timeout
178
+
179
+ def _build(self, client: httpx.Client | httpx.AsyncClient, request: ApiRequest) -> httpx.Request:
180
+ return client.build_request(
181
+ request.method,
182
+ f"{self._base_url}{request.path}",
183
+ params=dict(request.params),
184
+ json=request.json if request.method in ("POST", "PUT", "PATCH") else None,
185
+ headers=self._headers,
186
+ timeout=self._timeout,
187
+ )
188
+
189
+ def _build_upload(self, client: httpx.Client | httpx.AsyncClient, upload: FileUpload) -> httpx.Request:
190
+ # The presigned form is for the bucket, not the API: it never carries the API key.
191
+ return client.build_request(
192
+ "POST",
193
+ upload.url,
194
+ data=dict(upload.fields),
195
+ files={"file": ("file", upload.content, upload.content_type)},
196
+ headers={"user-agent": USER_AGENT},
197
+ timeout=self._timeout,
198
+ )
199
+
200
+
201
+ class SyncTransport(_BaseTransport):
202
+ """Sends requests with an :class:`httpx.Client`."""
203
+
204
+ def __init__(self, *, api_key: str, base_url: str, timeout: float, http_client: httpx.Client | None) -> None:
205
+ """Creates the transport; it owns the HTTP client only when none is given."""
206
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
207
+ self._owns_client = http_client is None
208
+ self._client = http_client if http_client is not None else httpx.Client()
209
+
210
+ def send(self, request: ApiRequest, adapter: TypeAdapter[T]) -> T:
211
+ """Sends a request and returns its typed body."""
212
+ try:
213
+ response = self._client.send(self._build(self._client, request))
214
+ except httpx.TimeoutException as error:
215
+ raise APITimeoutError from error
216
+ except httpx.TransportError as error:
217
+ raise APIConnectionError(f"Could not connect to the Templr API: {error}") from error
218
+ return parse_response(response, adapter)
219
+
220
+ def upload(self, upload: FileUpload) -> None:
221
+ """Sends a file to a presigned storage form."""
222
+ try:
223
+ response = self._client.send(self._build_upload(self._client, upload))
224
+ except httpx.TimeoutException as error:
225
+ raise APITimeoutError("The upload to the storage bucket timed out.") from error
226
+ except httpx.TransportError as error:
227
+ raise APIConnectionError(f"Could not connect to the storage bucket: {error}") from error
228
+ check_upload(response)
229
+
230
+ def close(self) -> None:
231
+ """Closes the HTTP client if the transport created it."""
232
+ if self._owns_client:
233
+ self._client.close()
234
+
235
+
236
+ class AsyncTransport(_BaseTransport):
237
+ """Sends requests with an :class:`httpx.AsyncClient`."""
238
+
239
+ def __init__(self, *, api_key: str, base_url: str, timeout: float, http_client: httpx.AsyncClient | None) -> None:
240
+ """Creates the transport; it owns the HTTP client only when none is given."""
241
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
242
+ self._owns_client = http_client is None
243
+ self._client = http_client if http_client is not None else httpx.AsyncClient()
244
+
245
+ async def send(self, request: ApiRequest, adapter: TypeAdapter[T]) -> T:
246
+ """Sends a request and returns its typed body."""
247
+ try:
248
+ response = await self._client.send(self._build(self._client, request))
249
+ except httpx.TimeoutException as error:
250
+ raise APITimeoutError from error
251
+ except httpx.TransportError as error:
252
+ raise APIConnectionError(f"Could not connect to the Templr API: {error}") from error
253
+ return parse_response(response, adapter)
254
+
255
+ async def upload(self, upload: FileUpload) -> None:
256
+ """Sends a file to a presigned storage form."""
257
+ try:
258
+ response = await self._client.send(self._build_upload(self._client, upload))
259
+ except httpx.TimeoutException as error:
260
+ raise APITimeoutError("The upload to the storage bucket timed out.") from error
261
+ except httpx.TransportError as error:
262
+ raise APIConnectionError(f"Could not connect to the storage bucket: {error}") from error
263
+ check_upload(response)
264
+
265
+ async def close(self) -> None:
266
+ """Closes the HTTP client if the transport created it."""
267
+ if self._owns_client:
268
+ await self._client.aclose()
templr/errors.py ADDED
@@ -0,0 +1,183 @@
1
+ """Errors raised by the Templr SDK.
2
+
3
+ Every error inherits from :class:`TemplrError` and carries a machine-readable
4
+ ``code``. Errors returned by the API are :class:`APIError` subclasses chosen by
5
+ HTTP status, with the ``code``, ``message`` and ``issues`` sent by the API.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class TemplrError(Exception):
12
+ """Base class of every error raised by the SDK.
13
+
14
+ Attributes:
15
+ code: A machine-readable error code.
16
+ message: A human-readable description of the error.
17
+ """
18
+
19
+ code: str
20
+ message: str
21
+
22
+ def __init__(self, message: str, *, code: str) -> None:
23
+ """Creates an error with its message and code."""
24
+ super().__init__(message)
25
+ self.code = code
26
+ self.message = message
27
+
28
+
29
+ class APIConnectionError(TemplrError):
30
+ """The request could not reach the Templr server (DNS, TLS, refused connection...)."""
31
+
32
+ def __init__(
33
+ self, message: str = "Could not connect to the Templr API.", *, code: str = "connection_error"
34
+ ) -> None:
35
+ """Creates a connection error."""
36
+ super().__init__(message, code=code)
37
+
38
+
39
+ class APITimeoutError(APIConnectionError):
40
+ """The request took longer than the configured timeout."""
41
+
42
+ def __init__(self, message: str = "The request to the Templr API timed out.") -> None:
43
+ """Creates a timeout error."""
44
+ super().__init__(message, code="timeout")
45
+
46
+
47
+ class UnexpectedResponseError(TemplrError):
48
+ """The API answered with a success status but a body the SDK does not understand.
49
+
50
+ This usually means the server runs a newer or older, incompatible version of the API.
51
+
52
+ Attributes:
53
+ status_code: The HTTP status of the response.
54
+ body: The raw response body.
55
+ """
56
+
57
+ status_code: int
58
+ body: str
59
+
60
+ def __init__(self, message: str, *, status_code: int, body: str) -> None:
61
+ """Creates an unexpected response error."""
62
+ super().__init__(message, code="unexpected_response")
63
+ self.status_code = status_code
64
+ self.body = body
65
+
66
+
67
+ class UploadError(TemplrError):
68
+ """The storage bucket rejected the file of an image upload.
69
+
70
+ The bucket rejects files of another type or size than the ones the upload
71
+ was started with, and uploads that expired.
72
+
73
+ Attributes:
74
+ status_code: The HTTP status of the bucket response.
75
+ body: The raw response body.
76
+ """
77
+
78
+ status_code: int
79
+ body: str
80
+
81
+ def __init__(self, message: str, *, status_code: int, body: str) -> None:
82
+ """Creates an upload error."""
83
+ super().__init__(message, code="upload_failed")
84
+ self.status_code = status_code
85
+ self.body = body
86
+
87
+
88
+ class APIError(TemplrError):
89
+ """The API answered with an error status.
90
+
91
+ Attributes:
92
+ status_code: The HTTP status of the response.
93
+ code: The error code sent by the API, e.g. ``not_found`` or ``validation_error``;
94
+ ``unknown_error`` when the response has no Templr error body.
95
+ message: The error message sent by the API.
96
+ issues: Every validation problem found; empty for other errors.
97
+ """
98
+
99
+ status_code: int
100
+ issues: tuple[str, ...]
101
+
102
+ def __init__(self, message: str, *, status_code: int, code: str, issues: tuple[str, ...] = ()) -> None:
103
+ """Creates an API error."""
104
+ super().__init__(message, code=code)
105
+ self.status_code = status_code
106
+ self.issues = issues
107
+
108
+ def __str__(self) -> str:
109
+ """Formats the error with its status and code."""
110
+ return f"{self.status_code} {self.code}: {self.message}"
111
+
112
+
113
+ class BadRequestError(APIError):
114
+ """400: the request is invalid (``invalid_input``, ``validation_error``)."""
115
+
116
+
117
+ class AuthenticationError(APIError):
118
+ """401: the API key is missing, unknown or expired (``unauthorized``)."""
119
+
120
+
121
+ class PermissionDeniedError(APIError):
122
+ """403: the API key scope does not allow this operation (``forbidden``)."""
123
+
124
+
125
+ class NotFoundError(APIError):
126
+ """404: the resource does not exist or belongs to another workspace (``not_found``)."""
127
+
128
+
129
+ class ConflictError(APIError):
130
+ """409: the resource is not in the expected state.
131
+
132
+ E.g. the file is not uploaded yet (``upload_missing``), or another variable
133
+ already has the new key (``conflict``).
134
+ """
135
+
136
+
137
+ class PayloadTooLargeError(APIError):
138
+ """413: the request body is too large (``payload_too_large``)."""
139
+
140
+
141
+ class RateLimitError(APIError):
142
+ """429: the API key is over its rate limit (``rate_limited``).
143
+
144
+ Attributes:
145
+ retry_after: Seconds to wait before retrying, from the ``Retry-After`` header, when sent.
146
+ """
147
+
148
+ retry_after: int | None
149
+
150
+ def __init__(
151
+ self,
152
+ message: str,
153
+ *,
154
+ status_code: int,
155
+ code: str,
156
+ issues: tuple[str, ...] = (),
157
+ retry_after: int | None = None,
158
+ ) -> None:
159
+ """Creates a rate limit error."""
160
+ super().__init__(message, status_code=status_code, code=code, issues=issues)
161
+ self.retry_after = retry_after
162
+
163
+
164
+ class InternalServerError(APIError):
165
+ """5xx: the server or its storage failed (``internal_error``, ``storage_error``, ``storage_not_configured``...)."""
166
+
167
+
168
+ __all__ = [
169
+ "APIConnectionError",
170
+ "APIError",
171
+ "APITimeoutError",
172
+ "AuthenticationError",
173
+ "BadRequestError",
174
+ "ConflictError",
175
+ "InternalServerError",
176
+ "NotFoundError",
177
+ "PayloadTooLargeError",
178
+ "PermissionDeniedError",
179
+ "RateLimitError",
180
+ "TemplrError",
181
+ "UnexpectedResponseError",
182
+ "UploadError",
183
+ ]