docunext 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.
docunext/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """The official Python client for the DocuNext document generation API. See https://www.docunext.app/docs."""
2
+
3
+ from ._client import Batches, DocuNext, Documents, Templates, __version__
4
+ from ._errors import DocuNextError, DocuNextSignatureError, DocuNextTimeoutError
5
+ from ._types import (
6
+ AcceptedBatch,
7
+ AcceptedDocument,
8
+ Batch,
9
+ BatchDocument,
10
+ BatchItem,
11
+ Document,
12
+ DocumentError,
13
+ GeneratedFile,
14
+ OutputFormat,
15
+ PdfStandard,
16
+ PngOptions,
17
+ RenderData,
18
+ Template,
19
+ WebhookEvent,
20
+ )
21
+ from ._webhooks import WEBHOOK_SIGNATURE_HEADER, construct_webhook_event, verify_webhook_signature
22
+
23
+ __all__ = [
24
+ "AcceptedBatch",
25
+ "AcceptedDocument",
26
+ "Batch",
27
+ "BatchDocument",
28
+ "BatchItem",
29
+ "Batches",
30
+ "DocuNext",
31
+ "DocuNextError",
32
+ "DocuNextSignatureError",
33
+ "DocuNextTimeoutError",
34
+ "Document",
35
+ "DocumentError",
36
+ "Documents",
37
+ "GeneratedFile",
38
+ "OutputFormat",
39
+ "PdfStandard",
40
+ "PngOptions",
41
+ "RenderData",
42
+ "Template",
43
+ "Templates",
44
+ "WEBHOOK_SIGNATURE_HEADER",
45
+ "WebhookEvent",
46
+ "__version__",
47
+ "construct_webhook_event",
48
+ "verify_webhook_signature",
49
+ ]
docunext/_client.py ADDED
@@ -0,0 +1,404 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import random
5
+ import time
6
+ from types import TracebackType
7
+ from typing import IO, Any, Callable, Dict, List, Optional, Sequence, Type, TypeVar, Union, cast
8
+ from urllib.parse import quote, unquote
9
+
10
+ import httpx
11
+
12
+ from ._errors import DocuNextError, DocuNextTimeoutError
13
+ from ._types import (
14
+ AcceptedBatch,
15
+ AcceptedDocument,
16
+ Batch,
17
+ BatchItem,
18
+ Document,
19
+ GeneratedFile,
20
+ OutputFormat,
21
+ PdfStandard,
22
+ PngOptions,
23
+ RenderData,
24
+ Template,
25
+ )
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ DEFAULT_BASE_URL = "https://www.docunext.app"
30
+ DEFAULT_TIMEOUT = 60.0
31
+ DEFAULT_MAX_RETRIES = 2
32
+ MAX_BACKOFF = 8.0
33
+
34
+ T = TypeVar("T")
35
+ FileInput = Union[bytes, bytearray, IO[bytes], str, "os.PathLike[str]"]
36
+
37
+
38
+ def _output_options(
39
+ output_format: Optional[OutputFormat],
40
+ pdf_standard: Optional[PdfStandard],
41
+ png_options: Optional[PngOptions],
42
+ ) -> Dict[str, Any]:
43
+ options: Dict[str, Any] = {}
44
+
45
+ if output_format is not None:
46
+ options["output_format"] = output_format
47
+ if pdf_standard is not None:
48
+ options["pdf_standard"] = pdf_standard
49
+ if png_options is not None:
50
+ options["png_options"] = dict(png_options)
51
+
52
+ return options
53
+
54
+
55
+ def _error_from(response: httpx.Response) -> DocuNextError:
56
+ code = "internal_error"
57
+ message = f"DocuNext returned HTTP {response.status_code}."
58
+
59
+ try:
60
+ error = response.json().get("error", {})
61
+ code = error.get("code") or code
62
+ message = error.get("message") or message
63
+ except (ValueError, AttributeError):
64
+ pass # The body was not the API's JSON error envelope; keep the generic message.
65
+
66
+ return DocuNextError(code, message, response.status_code, _retry_after(response))
67
+
68
+
69
+ def _retry_after(response: httpx.Response) -> Optional[float]:
70
+ try:
71
+ value = float(response.headers.get("retry-after", ""))
72
+ except ValueError:
73
+ return None
74
+
75
+ return value if value > 0 else None
76
+
77
+
78
+ class DocuNext:
79
+ """The DocuNext API client.
80
+
81
+ >>> client = DocuNext(api_key="dn_test_...")
82
+ >>> file = client.documents.generate(template_id, {"customer_name": "Acme"})
83
+
84
+ Use it as a context manager, or call ``close()``, to release its connections.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ api_key: Optional[str] = None,
90
+ *,
91
+ base_url: str = DEFAULT_BASE_URL,
92
+ timeout: float = DEFAULT_TIMEOUT,
93
+ max_retries: int = DEFAULT_MAX_RETRIES,
94
+ http_client: Optional[httpx.Client] = None,
95
+ ) -> None:
96
+ """
97
+ :param api_key: A live (dn_live_...) or test (dn_test_...) key. Defaults to the DOCUNEXT_API_KEY variable.
98
+ :param timeout: Seconds allowed for each request. Defaults to 60, the API's own limit.
99
+ :param max_retries: Retries for rate-limited requests, and for reads that hit a server or network error.
100
+ Generation requests are only retried when rate limited, so a document is never made twice.
101
+ :param http_client: An httpx.Client to use, for proxies or tests.
102
+ """
103
+ key = api_key or os.environ.get("DOCUNEXT_API_KEY")
104
+
105
+ if not key:
106
+ raise ValueError("Pass api_key or set the DOCUNEXT_API_KEY environment variable.")
107
+
108
+ self._api_key = key
109
+ self._base_url = base_url.rstrip("/")
110
+ self._max_retries = max_retries
111
+ self._owns_client = http_client is None
112
+ self._http = http_client or httpx.Client(timeout=timeout)
113
+ self._timeout = timeout
114
+ self._sleep: Callable[[float], None] = time.sleep
115
+
116
+ self.templates = Templates(self)
117
+ self.documents = Documents(self)
118
+ self.batches = Batches(self)
119
+
120
+ def close(self) -> None:
121
+ if self._owns_client:
122
+ self._http.close()
123
+
124
+ def __enter__(self) -> "DocuNext":
125
+ return self
126
+
127
+ def __exit__(
128
+ self,
129
+ exc_type: Optional[Type[BaseException]],
130
+ exc: Optional[BaseException],
131
+ traceback: Optional[TracebackType],
132
+ ) -> None:
133
+ self.close()
134
+
135
+ def _request(
136
+ self,
137
+ method: str,
138
+ path: str,
139
+ *,
140
+ json: Any = None,
141
+ files: Any = None,
142
+ data: Any = None,
143
+ safe_to_retry: bool,
144
+ ) -> httpx.Response:
145
+ headers = {
146
+ "Authorization": f"Bearer {self._api_key}",
147
+ "Accept": "application/json",
148
+ "User-Agent": f"docunext-python/{__version__}",
149
+ }
150
+ attempt = 0
151
+
152
+ while True:
153
+ try:
154
+ response = self._http.request(
155
+ method,
156
+ f"{self._base_url}{path}",
157
+ headers=headers,
158
+ json=json,
159
+ files=files,
160
+ data=data,
161
+ timeout=self._timeout,
162
+ )
163
+ except httpx.TransportError as error:
164
+ # The request may have reached DocuNext, so only reads are retried.
165
+ if safe_to_retry and attempt < self._max_retries:
166
+ self._sleep(self._backoff(attempt))
167
+ attempt += 1
168
+ continue
169
+
170
+ raise DocuNextError("network_error", f"Could not reach DocuNext: {error}", 0) from error
171
+
172
+ if response.is_success:
173
+ return response
174
+
175
+ # A rate-limited request was refused before any work, so it is always safe to send again.
176
+ retryable = response.status_code == 429 or (safe_to_retry and response.status_code >= 500)
177
+
178
+ if retryable and attempt < self._max_retries:
179
+ self._sleep(self._backoff(attempt, _retry_after(response)))
180
+ attempt += 1
181
+ continue
182
+
183
+ raise _error_from(response)
184
+
185
+ @staticmethod
186
+ def _backoff(attempt: int, retry_after: Optional[float] = None) -> float:
187
+ if retry_after is not None:
188
+ return min(retry_after, MAX_BACKOFF * 4)
189
+
190
+ # Exponential backoff with jitter: about 0.5 s, 1 s, 2 s, ... capped.
191
+ return float(min(MAX_BACKOFF, 0.5 * 2**attempt) * (0.75 + random.random() * 0.5))
192
+
193
+ def _poll(
194
+ self,
195
+ id: str,
196
+ load: Callable[[], T],
197
+ is_done: Callable[[T], bool],
198
+ interval: float,
199
+ timeout: float,
200
+ ) -> T:
201
+ deadline = time.monotonic() + timeout
202
+
203
+ while True:
204
+ value = load()
205
+
206
+ if is_done(value):
207
+ return value
208
+
209
+ if time.monotonic() + interval > deadline:
210
+ raise DocuNextTimeoutError(id, timeout)
211
+
212
+ self._sleep(interval)
213
+
214
+
215
+ class Templates:
216
+ def __init__(self, client: DocuNext) -> None:
217
+ self._client = client
218
+
219
+ def list(self) -> List[Template]:
220
+ """The workspace's templates, with the data each one expects."""
221
+ response = self._client._request("GET", "/api/v1/templates", safe_to_retry=True)
222
+
223
+ return cast(List[Template], response.json()["templates"])
224
+
225
+ def upload(self, file: FileInput, filename: Optional[str] = None, *, folder_id: Optional[str] = None) -> Template:
226
+ """Uploads a DOCX, DOTX or ODT template of up to 10 MB.
227
+
228
+ ``file`` may be bytes, an open binary file, or a path.
229
+ """
230
+ if isinstance(file, (str, os.PathLike)):
231
+ path = os.fspath(file)
232
+ with open(path, "rb") as handle:
233
+ content = handle.read()
234
+ filename = filename or os.path.basename(path)
235
+ elif isinstance(file, (bytes, bytearray)):
236
+ content = bytes(file)
237
+ else:
238
+ content = file.read()
239
+ filename = filename or os.path.basename(getattr(file, "name", "") or "")
240
+
241
+ if not filename:
242
+ raise ValueError("Pass filename, such as 'invoice.docx', so DocuNext can tell the template type.")
243
+
244
+ response = self._client._request(
245
+ "POST",
246
+ "/api/v1/templates",
247
+ files={"file": (filename, content)},
248
+ data={"folder_id": folder_id} if folder_id else None,
249
+ safe_to_retry=False,
250
+ )
251
+
252
+ return cast(Template, response.json()["template"])
253
+
254
+
255
+ class Documents:
256
+ def __init__(self, client: DocuNext) -> None:
257
+ self._client = client
258
+
259
+ def _body(
260
+ self,
261
+ template_id: str,
262
+ data: RenderData,
263
+ output_format: Optional[OutputFormat],
264
+ pdf_standard: Optional[PdfStandard],
265
+ png_options: Optional[PngOptions],
266
+ output_filename: Optional[str],
267
+ is_async: bool,
268
+ ) -> Dict[str, Any]:
269
+ body: Dict[str, Any] = {
270
+ "template_id": template_id,
271
+ "data": data,
272
+ "async": is_async,
273
+ **_output_options(output_format, pdf_standard, png_options),
274
+ }
275
+
276
+ if output_filename is not None:
277
+ body["output_filename"] = output_filename
278
+
279
+ return body
280
+
281
+ def generate(
282
+ self,
283
+ template_id: str,
284
+ data: RenderData,
285
+ *,
286
+ output_format: Optional[OutputFormat] = None,
287
+ pdf_standard: Optional[PdfStandard] = None,
288
+ png_options: Optional[PngOptions] = None,
289
+ output_filename: Optional[str] = None,
290
+ ) -> GeneratedFile:
291
+ """Generates a document and returns the file. PDF is the default output format."""
292
+ response = self._client._request(
293
+ "POST",
294
+ "/api/v1/documents/generate",
295
+ json=self._body(template_id, data, output_format, pdf_standard, png_options, output_filename, False),
296
+ safe_to_retry=False,
297
+ )
298
+ encoded_filename = response.headers.get("x-document-filename")
299
+
300
+ return GeneratedFile(
301
+ content=response.content,
302
+ filename=unquote(encoded_filename) if encoded_filename else "document",
303
+ content_type=response.headers.get("content-type", "application/octet-stream"),
304
+ document_id=response.headers.get("x-document-id", ""),
305
+ test=response.headers.get("x-test-mode") == "true",
306
+ quota_warning=response.headers.get("x-quota-warning"),
307
+ )
308
+
309
+ def generate_async(
310
+ self,
311
+ template_id: str,
312
+ data: RenderData,
313
+ *,
314
+ output_format: Optional[OutputFormat] = None,
315
+ pdf_standard: Optional[PdfStandard] = None,
316
+ png_options: Optional[PngOptions] = None,
317
+ output_filename: Optional[str] = None,
318
+ ) -> AcceptedDocument:
319
+ """Queues a document for background generation and returns its ID straight away."""
320
+ response = self._client._request(
321
+ "POST",
322
+ "/api/v1/documents/generate",
323
+ json=self._body(template_id, data, output_format, pdf_standard, png_options, output_filename, True),
324
+ safe_to_retry=False,
325
+ )
326
+
327
+ return cast(AcceptedDocument, response.json())
328
+
329
+ def get(self, id: str) -> Document:
330
+ """A document's status and, once completed, a download link valid for one hour."""
331
+ response = self._client._request("GET", f"/api/v1/documents/{quote(id, safe='')}", safe_to_retry=True)
332
+
333
+ return cast(Document, response.json())
334
+
335
+ def wait_for(self, id: str, *, interval: float = 2.0, timeout: float = 120.0) -> Document:
336
+ """Waits until a queued document has completed or failed, checking every ``interval`` seconds."""
337
+ return self._client._poll(
338
+ id,
339
+ lambda: self.get(id),
340
+ lambda document: document["status"] not in ("queued", "processing"),
341
+ interval,
342
+ timeout,
343
+ )
344
+
345
+ def download(self, id: str) -> bytes:
346
+ """Downloads a completed document's file, fetching a fresh download link first."""
347
+ document = self.get(id)
348
+ url = document["download_url"]
349
+
350
+ if document["status"] != "completed" or not url:
351
+ error = document["error"]
352
+ raise DocuNextError(
353
+ error["code"] if error else "document_not_ready",
354
+ error["message"] if error else f"The document is {document['status']}, so there is no file to download.",
355
+ 409,
356
+ )
357
+
358
+ try:
359
+ response = self._client._http.get(url, timeout=self._client._timeout)
360
+ except httpx.TransportError as error:
361
+ raise DocuNextError("network_error", f"Could not download the document: {error}", 0) from error
362
+
363
+ if not response.is_success:
364
+ raise DocuNextError("download_failed", f"The download failed with HTTP {response.status_code}.", response.status_code)
365
+
366
+ return response.content
367
+
368
+
369
+ class Batches:
370
+ def __init__(self, client: DocuNext) -> None:
371
+ self._client = client
372
+
373
+ def create(
374
+ self,
375
+ template_id: str,
376
+ items: Sequence[BatchItem],
377
+ *,
378
+ output_format: Optional[OutputFormat] = None,
379
+ pdf_standard: Optional[PdfStandard] = None,
380
+ png_options: Optional[PngOptions] = None,
381
+ ) -> AcceptedBatch:
382
+ """Queues up to 100 documents from one template. Each item is {"data": {...}, "output_filename": "..."}."""
383
+ response = self._client._request(
384
+ "POST",
385
+ "/api/v1/documents/batch",
386
+ json={
387
+ "template_id": template_id,
388
+ "items": [dict(item) for item in items],
389
+ **_output_options(output_format, pdf_standard, png_options),
390
+ },
391
+ safe_to_retry=False,
392
+ )
393
+
394
+ return cast(AcceptedBatch, response.json())
395
+
396
+ def get(self, id: str) -> Batch:
397
+ """A batch's progress and each of its documents in request order."""
398
+ response = self._client._request("GET", f"/api/v1/batches/{quote(id, safe='')}", safe_to_retry=True)
399
+
400
+ return cast(Batch, response.json())
401
+
402
+ def wait_for(self, id: str, *, interval: float = 2.0, timeout: float = 600.0) -> Batch:
403
+ """Waits until every document in the batch has finished. Defaults to a 10 minute limit."""
404
+ return self._client._poll(id, lambda: self.get(id), lambda batch: batch["status"] != "processing", interval, timeout)
docunext/_errors.py ADDED
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class DocuNextError(Exception):
7
+ """An error response from the API, or a request that could not be completed.
8
+
9
+ ``code`` is the API's machine-readable error code, such as ``"missing_field"``, so callers can branch on it.
10
+ ``network_error`` (status 0) means the request could not reach DocuNext.
11
+ """
12
+
13
+ def __init__(self, code: str, message: str, status: int, retry_after: Optional[float] = None) -> None:
14
+ super().__init__(message)
15
+ self.code = code
16
+ self.message = message
17
+ #: The HTTP status, or 0 when no response came back.
18
+ self.status = status
19
+ #: For rate_limit_exceeded, seconds until a retry is allowed.
20
+ self.retry_after = retry_after
21
+
22
+ def __repr__(self) -> str:
23
+ return f"DocuNextError(code={self.code!r}, status={self.status}, message={self.message!r})"
24
+
25
+
26
+ class DocuNextTimeoutError(Exception):
27
+ """Waiting for a document or batch took longer than the timeout given. The work may still finish later."""
28
+
29
+ def __init__(self, id: str, timeout: float) -> None:
30
+ super().__init__(f"{id} did not finish within {timeout:g} seconds. It may still finish; check it again later.")
31
+ self.id = id
32
+
33
+
34
+ class DocuNextSignatureError(Exception):
35
+ """A webhook request whose signature is missing, wrong or too old."""
docunext/_types.py ADDED
@@ -0,0 +1,123 @@
1
+ """Types for the DocuNext REST API. Field names match the API and its docs at https://www.docunext.app/docs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, List, Optional, Union
8
+
9
+ if sys.version_info >= (3, 11):
10
+ from typing import Literal, NotRequired, TypedDict
11
+ else: # pragma: no cover - older Pythons
12
+ from typing_extensions import Literal, NotRequired, TypedDict
13
+
14
+ OutputFormat = Literal["pdf", "docx", "odt", "png"]
15
+ PdfStandard = Literal["PDF/A-1b", "PDF/A-2b", "PDF/A-3b"]
16
+ DocumentStatus = Literal["queued", "processing", "completed", "failed", "expired"]
17
+ BatchStatus = Literal["processing", "completed", "completed_with_errors"]
18
+
19
+ #: Render data: text, numbers, booleans, None, lists and nested dictionaries.
20
+ RenderData = Dict[str, Any]
21
+
22
+
23
+ class PngOptions(TypedDict, total=False):
24
+ page: int
25
+ width: int
26
+
27
+
28
+ class Template(TypedDict):
29
+ id: str
30
+ name: str
31
+ filename: str
32
+ status: Literal["ready", "processing", "failed"]
33
+ updated_at: str
34
+ #: Top-level data keys the template uses.
35
+ fields: List[str]
36
+ #: Keys that must be present in data.
37
+ required_fields: List[str]
38
+ #: A JSON Schema (draft 2020-12) for the data object.
39
+ data_schema: Dict[str, Any]
40
+ #: An example data object with the template's structure and empty values.
41
+ sample_data: Dict[str, Any]
42
+ folder_id: NotRequired[Optional[str]]
43
+
44
+
45
+ class DocumentError(TypedDict):
46
+ code: str
47
+ message: str
48
+
49
+
50
+ class Document(TypedDict):
51
+ id: str
52
+ status: DocumentStatus
53
+ filename: str
54
+ output_format: OutputFormat
55
+ pages: Optional[int]
56
+ test: bool
57
+ batch_id: Optional[str]
58
+ created_at: str
59
+ completed_at: Optional[str]
60
+ expires_at: str
61
+ #: A signed link valid until download_url_expires_at. None unless completed.
62
+ download_url: Optional[str]
63
+ download_url_expires_at: Optional[str]
64
+ error: Optional[DocumentError]
65
+
66
+
67
+ class BatchDocument(Document):
68
+ index: int
69
+
70
+
71
+ class Batch(TypedDict):
72
+ id: str
73
+ status: BatchStatus
74
+ test: bool
75
+ total: int
76
+ succeeded: int
77
+ failed: int
78
+ created_at: str
79
+ completed_at: Optional[str]
80
+ documents: List[BatchDocument]
81
+
82
+
83
+ class AcceptedDocument(TypedDict):
84
+ id: str
85
+ status: Literal["queued"]
86
+ status_url: str
87
+
88
+
89
+ class AcceptedBatch(TypedDict):
90
+ id: str
91
+ status: Literal["processing"]
92
+ total: int
93
+ status_url: str
94
+
95
+
96
+ class BatchItem(TypedDict, total=False):
97
+ data: RenderData
98
+ output_filename: str
99
+
100
+
101
+ class WebhookEvent(TypedDict):
102
+ #: The event ID. Use it to ignore repeated deliveries.
103
+ id: str
104
+ type: Literal["document.completed", "document.failed", "batch.completed", "webhook.test"]
105
+ created_at: str
106
+ test: bool
107
+ #: A Document, a Batch, or {"message": ...} for webhook.test.
108
+ data: Union[Document, Batch, Dict[str, Any]]
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class GeneratedFile:
113
+ """A file returned by a sync generation."""
114
+
115
+ content: bytes
116
+ filename: str
117
+ content_type: str
118
+ #: The document ID, for documents.get(). Sync test documents are not stored.
119
+ document_id: str
120
+ #: True when a test key generated the file.
121
+ test: bool
122
+ #: Set when the workspace is over its included documents.
123
+ quota_warning: Optional[str]
docunext/_webhooks.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import re
7
+ import time
8
+ from typing import Optional, Union, cast
9
+
10
+ from ._errors import DocuNextSignatureError
11
+ from ._types import WebhookEvent
12
+
13
+ WEBHOOK_SIGNATURE_HEADER = "DocuNext-Signature"
14
+ DEFAULT_TOLERANCE_SECONDS = 300
15
+
16
+ _HEX_SIGNATURE = re.compile(r"^[0-9a-fA-F]{64}$")
17
+
18
+
19
+ def verify_webhook_signature(
20
+ raw_body: Union[str, bytes],
21
+ signature_header: Optional[str],
22
+ secret: str,
23
+ *,
24
+ tolerance: int = DEFAULT_TOLERANCE_SECONDS,
25
+ now: Optional[float] = None,
26
+ ) -> bool:
27
+ """Checks a webhook request's DocuNext-Signature header against the endpoint's signing secret.
28
+
29
+ Pass the raw request body exactly as received (for example ``request.get_data()`` in Flask or
30
+ ``await request.body()`` in FastAPI): parsing and re-serialising the JSON changes the bytes and breaks the
31
+ signature.
32
+ """
33
+ if not signature_header or not secret:
34
+ return False
35
+
36
+ parts = {}
37
+ for part in signature_header.split(","):
38
+ key, _, value = part.partition("=")
39
+ parts[key.strip()] = value.strip()
40
+
41
+ timestamp = parts.get("t", "")
42
+ signature = parts.get("v1", "")
43
+ current = time.time() if now is None else now
44
+
45
+ if not timestamp.isdigit() or abs(current - int(timestamp)) > tolerance:
46
+ return False
47
+
48
+ if not _HEX_SIGNATURE.match(signature):
49
+ return False
50
+
51
+ body = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
52
+ expected = hmac.new(secret.encode("utf-8"), f"{timestamp}.".encode("utf-8") + body, hashlib.sha256).hexdigest()
53
+
54
+ return hmac.compare_digest(expected, signature.lower())
55
+
56
+
57
+ def construct_webhook_event(
58
+ raw_body: Union[str, bytes],
59
+ signature_header: Optional[str],
60
+ secret: str,
61
+ *,
62
+ tolerance: int = DEFAULT_TOLERANCE_SECONDS,
63
+ now: Optional[float] = None,
64
+ ) -> WebhookEvent:
65
+ """Verifies a webhook request and returns its event.
66
+
67
+ Raises DocuNextSignatureError when the signature is missing, wrong or too old.
68
+ """
69
+ if not verify_webhook_signature(raw_body, signature_header, secret, tolerance=tolerance, now=now):
70
+ raise DocuNextSignatureError("The webhook signature is missing, invalid or too old.")
71
+
72
+ return cast(WebhookEvent, json.loads(raw_body))
docunext/py.typed ADDED
File without changes
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.5
2
+ Name: docunext
3
+ Version: 0.1.0
4
+ Summary: Official Python client for the DocuNext document generation API.
5
+ Project-URL: Homepage, https://www.docunext.app
6
+ Project-URL: Documentation, https://www.docunext.app/docs
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: api,document generation,docunext,docx,pdf,templates
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Office/Business
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: httpx<1,>=0.27
19
+ Requires-Dist: typing-extensions>=4.7; python_version < '3.11'
20
+ Provides-Extra: dev
21
+ Requires-Dist: mypy>=1.10; extra == 'dev'
22
+ Requires-Dist: pytest>=8; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # DocuNext for Python
26
+
27
+ The official Python client for [DocuNext](https://www.docunext.app): fill DOCX, DOTX and ODT templates with JSON
28
+ data and get PDF, PDF/A, DOCX, ODT or PNG files back.
29
+
30
+ - Typed responses (TypedDicts), errors and webhook events
31
+ - Retries rate-limited requests and failed reads; never repeats a generation
32
+ - Helpers to wait for async documents and batches, and to download files
33
+ - Webhook signature verification
34
+ - Python 3.10 or later. One dependency: [httpx](https://www.python-httpx.org).
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install docunext
40
+ ```
41
+
42
+ ## Quick start
43
+
44
+ Create an API key on the [API keys page](https://www.docunext.app/dashboard/api-keys). Use a test key
45
+ (`dn_test_…`) while you build: test documents are free and watermarked.
46
+
47
+ ```python
48
+ from docunext import DocuNext
49
+
50
+ client = DocuNext() # reads DOCUNEXT_API_KEY, or pass api_key="dn_test_..."
51
+
52
+ template = client.templates.list()[0]
53
+ file = client.documents.generate(
54
+ template["id"],
55
+ {"customer_name": "Acme Pty Ltd", "items": [{"description": "Widget", "qty": 2}]},
56
+ output_format="pdf",
57
+ )
58
+
59
+ with open(file.filename, "wb") as handle:
60
+ handle.write(file.content)
61
+ ```
62
+
63
+ `template["sample_data"]` shows the data a template expects, and `template["data_schema"]` is a JSON Schema for it.
64
+
65
+ ## Async documents
66
+
67
+ For long documents, generate in the background and wait, or let a webhook tell you when it is ready.
68
+
69
+ ```python
70
+ accepted = client.documents.generate_async(template_id, data)
71
+ document = client.documents.wait_for(accepted["id"]) # checks every 2 seconds, up to 2 minutes
72
+
73
+ if document["status"] == "completed":
74
+ pdf = client.documents.download(accepted["id"])
75
+ ```
76
+
77
+ ## Batches
78
+
79
+ Up to 100 documents from one template in one request:
80
+
81
+ ```python
82
+ batch = client.batches.create(
83
+ template_id,
84
+ [{"data": invoice, "output_filename": f"invoice-{invoice['number']}"} for invoice in invoices],
85
+ output_format="pdf",
86
+ )
87
+
88
+ finished = client.batches.wait_for(batch["id"])
89
+
90
+ for document in finished["documents"]:
91
+ if document["status"] == "completed":
92
+ print(document["index"], document["download_url"])
93
+ else:
94
+ print(document["index"], document["error"])
95
+ ```
96
+
97
+ ## Errors
98
+
99
+ Failed requests raise `DocuNextError` with the API's machine-readable `code` and HTTP `status`:
100
+
101
+ ```python
102
+ from docunext import DocuNextError
103
+
104
+ try:
105
+ client.documents.generate(template_id, {})
106
+ except DocuNextError as error:
107
+ if error.code == "missing_field":
108
+ print(error.message) # "Missing field: customer_name"
109
+ else:
110
+ raise
111
+ ```
112
+
113
+ Every code is listed in the [API reference](https://www.docunext.app/docs#errors). `network_error` (status 0) means
114
+ the request could not reach DocuNext.
115
+
116
+ ## Webhooks
117
+
118
+ Check each webhook request against your endpoint's signing secret, using the **raw** request body:
119
+
120
+ ```python
121
+ import os
122
+
123
+ from flask import Flask, request
124
+ from docunext import DocuNextSignatureError, construct_webhook_event
125
+
126
+ app = Flask(__name__)
127
+
128
+
129
+ @app.post("/webhooks/docunext")
130
+ def docunext_webhook():
131
+ try:
132
+ event = construct_webhook_event(
133
+ request.get_data(),
134
+ request.headers.get("DocuNext-Signature"),
135
+ os.environ["DOCUNEXT_WEBHOOK_SECRET"],
136
+ )
137
+ except DocuNextSignatureError:
138
+ return "Invalid signature", 400
139
+
140
+ if event["type"] == "document.completed":
141
+ ... # event["data"] is the document, with a download_url valid for an hour.
142
+
143
+ return "", 200
144
+ ```
145
+
146
+ `verify_webhook_signature(raw_body, header, secret)` returns `True` or `False` if you prefer to handle it yourself.
147
+
148
+ ## Options
149
+
150
+ ```python
151
+ DocuNext(
152
+ api_key="dn_live_...", # defaults to the DOCUNEXT_API_KEY environment variable
153
+ timeout=60.0, # seconds per request
154
+ max_retries=2, # rate limits always; reads also after server and network errors
155
+ base_url="https://www.docunext.app",
156
+ http_client=None, # your own httpx.Client, for proxies
157
+ )
158
+ ```
159
+
160
+ Use the client as a context manager (`with DocuNext() as client:`) or call `client.close()` when you are done.
161
+
162
+ ## Links
163
+
164
+ - [API reference](https://www.docunext.app/docs)
165
+ - [Template syntax](https://www.docunext.app/docs#template-syntax)
166
+ - [Making a template](https://www.docunext.app/docs/templates)
167
+
168
+ ## License
169
+
170
+ MIT
@@ -0,0 +1,10 @@
1
+ docunext/__init__.py,sha256=oCT-yYE8DfNNft868g1aDVVQVZuvjxJ_YStr9qNX_dg,1164
2
+ docunext/_client.py,sha256=qaK-h1rL55oapy5OlN64EzOAOgv3UZuf7mxfDbQOEx8,13946
3
+ docunext/_errors.py,sha256=dQitxmUMwSki6Y2qA2V92IUSXrjtlbrhVeuoy0wHobo,1375
4
+ docunext/_types.py,sha256=EpYT5B0psFEHGz4BjW10E9bWT7f3TELXHXpgm8FsOVk,3261
5
+ docunext/_webhooks.py,sha256=a2IpIVE7Q7u17sNe8cWfNX2mHOOLJR7hteunw5rrtCE,2278
6
+ docunext/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ docunext-0.1.0.dist-info/METADATA,sha256=rcJBB-AV58dP4RRflQ9_6anuq52fed7aSP0G6OhFtq0,5125
8
+ docunext-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ docunext-0.1.0.dist-info/licenses/LICENSE,sha256=MH8QgOmE7092tYS3t6LOgCb_Rr1NiFPjVVzd2EJ6NGY,1065
10
+ docunext-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DocuNext
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.