docunext
Official Python client for the DocuNext document generation API.
Downloads & Community Adoption
Health & Engineering Analysis (5 Pillars)
1. Governance & Community50 / 200 ▾
2. PEP Metadata & Packaging200 / 200 ▾
3. Security & Supply Chain150 / 200 ▾
4. Documentation, SEO & Ecosystem155 / 200 ▾
5. Engineering, CI & Quality0 / 200 ▾
Official Documentation & Usage Guide — docunext
Show full original documentation (English README) ▾
DocuNext for Python
The official Python client for DocuNext: fill DOCX, DOTX, ODT and OTT templates with JSON data and get PDF, PDF/A, DOCX, ODT 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.
Install
pip install docunext
Quick start
Create an API key on the API keys page. Use a test key
(dn_test_…) while you build: test documents are free and watermarked.
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.
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:
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:
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. 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:
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
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
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
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 TypedDicts, so editors complete them. The
API reference 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" 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
License
MIT