Metadata-Version: 2.5
Name: docunext
Version: 0.2.0
Summary: Official Python client for the DocuNext document generation API.
Project-URL: Homepage, https://www.docunext.app
Project-URL: Documentation, https://www.docunext.app/docs
License-Expression: MIT
License-File: LICENSE
Keywords: api,document generation,docunext,docx,pdf,templates
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Office/Business
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: typing-extensions>=4.7; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# DocuNext for Python

The official Python client for [DocuNext](https://www.docunext.app): fill Word, Excel and OpenDocument templates with JSON
data and get PDF, PDF/A, DOCX, ODT, XLSX or PNG files back.

- Typed responses (TypedDicts), errors and webhook events
- Retries rate-limited requests and failed reads; never repeats a generation
- Helpers to wait for async documents and batches, and to download files
- Webhook signature verification
- Python 3.10 or later. One dependency: [httpx](https://www.python-httpx.org).

## Install

```bash
pip install docunext
```

## Quick start

Create an API key on the [API keys page](https://www.docunext.app/dashboard/api-keys). Use a test key
(`dn_test_…`) while you build: test documents are free and watermarked.

```python
from docunext import DocuNext

client = DocuNext()  # reads DOCUNEXT_API_KEY, or pass api_key="dn_test_..."

template = client.templates.list()[0]
file = client.documents.generate(
    template["id"],
    {"customer_name": "Acme Pty Ltd", "items": [{"description": "Widget", "qty": 2}]},
    output_format="pdf",
)

with open(file.filename, "wb") as handle:
    handle.write(file.content)
```

`template["sample_data"]` shows the data a template expects, and `template["data_schema"]` is a JSON Schema for it.

## Async documents

For long documents, generate in the background and wait, or let a webhook tell you when it is ready.

```python
accepted = client.documents.generate_async(template_id, data)
document = client.documents.wait_for(accepted["id"])  # checks every 2 seconds, up to 2 minutes

if document["status"] == "completed":
    pdf = client.documents.download(accepted["id"])
```

## Batches

Up to 100 documents from one template in one request:

```python
batch = client.batches.create(
    template_id,
    [{"data": invoice, "output_filename": f"invoice-{invoice['number']}"} for invoice in invoices],
    output_format="pdf",
)

finished = client.batches.wait_for(batch["id"])

for document in finished["documents"]:
    if document["status"] == "completed":
        print(document["index"], document["download_url"])
    else:
        print(document["index"], document["error"])
```

## Errors

Failed requests raise `DocuNextError` with the API's machine-readable `code` and HTTP `status`:

```python
from docunext import DocuNextError

try:
    client.documents.generate(template_id, {})
except DocuNextError as error:
    if error.code == "missing_field":
        print(error.message)  # "Missing field: customer_name"
    else:
        raise
```

Every code is listed in the [API reference](https://www.docunext.app/docs#errors). `network_error` (status 0) means
the request could not reach DocuNext.

## Webhooks

Check each webhook request against your endpoint's signing secret, using the **raw** request body:

```python
import os

from flask import Flask, request
from docunext import DocuNextSignatureError, construct_webhook_event

app = Flask(__name__)


@app.post("/webhooks/docunext")
def docunext_webhook():
    try:
        event = construct_webhook_event(
            request.get_data(),
            request.headers.get("DocuNext-Signature"),
            os.environ["DOCUNEXT_WEBHOOK_SECRET"],
        )
    except DocuNextSignatureError:
        return "Invalid signature", 400

    if event["type"] == "document.completed":
        ...  # event["data"] is the document, with a download_url valid for an hour.

    return "", 200
```

### FastAPI

```python
import os
from typing import Optional

from fastapi import FastAPI, Header, HTTPException, Request
from docunext import DocuNextSignatureError, construct_webhook_event

app = FastAPI()


@app.post("/webhooks/docunext")
async def docunext_webhook(request: Request, docunext_signature: Optional[str] = Header(default=None)):
    try:
        event = construct_webhook_event(
            await request.body(),  # the raw bytes, before any JSON parsing
            docunext_signature,
            os.environ["DOCUNEXT_WEBHOOK_SECRET"],
        )
    except DocuNextSignatureError:
        raise HTTPException(status_code=400, detail="Invalid signature")

    if event["type"] == "batch.completed":
        ...  # event["data"] is the batch, with every document's result.

    return {"received": True}
```

### Django

```python
import os

from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from docunext import DocuNextSignatureError, construct_webhook_event


@csrf_exempt  # DocuNext signs its requests instead of sending a CSRF token.
@require_POST
def docunext_webhook(request):
    try:
        event = construct_webhook_event(
            request.body,
            request.headers.get("DocuNext-Signature"),
            os.environ["DOCUNEXT_WEBHOOK_SECRET"],
        )
    except DocuNextSignatureError:
        return HttpResponseBadRequest("Invalid signature")

    if event["type"] == "document.failed":
        ...  # event["data"]["error"] has the code and message.

    return HttpResponse(status=200)
```

`verify_webhook_signature(raw_body, header, secret)` returns `True` or `False` if you prefer to handle it yourself.
Reply quickly (DocuNext waits 10 seconds) and use `event["id"]` to ignore repeated deliveries.

## Options

```python
DocuNext(
    api_key="dn_live_...",  # defaults to the DOCUNEXT_API_KEY environment variable
    timeout=60.0,  # seconds per request
    max_retries=2,  # rate limits always; reads also after server and network errors
    base_url="https://www.docunext.app",
    http_client=None,  # your own httpx.Client, for proxies
)
```

Use the client as a context manager (`with DocuNext() as client:`) or call `client.close()` when you are done.

## Reference

Responses are dictionaries with the same fields as the API, typed as `TypedDict`s, so editors complete them. The
[API reference](https://www.docunext.app/docs) describes every field.

### `client.templates`

| Method | Returns |
| --- | --- |
| `list()` | `list[Template]`: each template's `id`, `name`, `fields`, `required_fields`, `data_schema` and `sample_data` |
| `upload(file, filename=None, *, folder_id=None)` | `Template`. `file` is bytes, an open binary file or a path; `filename` is needed for bytes |

### `client.documents`

| Method | Returns |
| --- | --- |
| `generate(template_id, data, *, output_format=None, pdf_standard=None, png_options=None, output_filename=None)` | `GeneratedFile` with `content` (bytes), `filename`, `content_type`, `document_id`, `test` and `quota_warning` |
| `generate_async(...)`, same arguments | `AcceptedDocument`: `id`, `status` (`"queued"`) and `status_url` |
| `get(id)` | `Document`: `status`, `filename`, `pages`, `download_url` (valid one hour), `error` and more |
| `wait_for(id, *, interval=2.0, timeout=120.0)` | The finished `Document`; raises `DocuNextTimeoutError` after `timeout` seconds |
| `download(id)` | The file as `bytes`; raises `DocuNextError` if the document is not completed |

`output_format` is `"pdf"` (default), `"docx"`, `"odt"`, `"xlsx"` or `"png"`. `pdf_standard` is `"PDF/A-1b"`, `"PDF/A-2b"` or
`"PDF/A-3b"`. `png_options` is `{"page": 1, "width": 1240}`. `output_filename` has no extension.

### `client.batches`

| Method | Returns |
| --- | --- |
| `create(template_id, items, *, output_format=None, pdf_standard=None, png_options=None)` | `AcceptedBatch`: `id`, `status` and `total`. `items` is up to 100 `{"data": {...}, "output_filename": "..."}` |
| `get(id)` | `Batch`: `status`, `succeeded`, `failed` and `documents`, each with its `index` |
| `wait_for(id, *, interval=2.0, timeout=600.0)` | The finished `Batch`; raises `DocuNextTimeoutError` after `timeout` seconds |

### Webhooks

| Function | Returns |
| --- | --- |
| `construct_webhook_event(raw_body, header, secret, *, tolerance=300)` | The `WebhookEvent`; raises `DocuNextSignatureError` if the signature is missing, wrong or older than `tolerance` seconds |
| `verify_webhook_signature(raw_body, header, secret, *, tolerance=300)` | `True` or `False` |

### Errors

| Exception | When |
| --- | --- |
| `DocuNextError` | The API returned an error, or the request could not be sent. Has `code`, `message`, `status` and, when rate limited, `retry_after` |
| `DocuNextTimeoutError` | `wait_for` gave up. Has the `id`; the work may still finish |
| `DocuNextSignatureError` | `construct_webhook_event` rejected a request |

## Links

- [API reference](https://www.docunext.app/docs)
- [Template syntax](https://www.docunext.app/docs#template-syntax)
- [Making a template](https://www.docunext.app/docs/templates)

## License

MIT
