Skip to main content

DocuNext for Python

The official Python client for DocuNext: 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.

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", "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

License

MIT

Metadata

Release files for docunext 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for docunext 0.2.0
File Size Uploaded Provenance Actions
docunext-0.2.0.tar.gz 14.5 kB With provenance Details for docunext-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for docunext 0.2.0
File Interpreter ABI Platform Actions
docunext-0.2.0-py3-none-any.whl Python 3 none any Details for docunext-0.2.0-py3-none-any.whl

Total release size: 27.8 kB

Release files / docunext-0.2.0.tar.gz

Download URL docunext-0.2.0.tar.gz
Size 14.5 kB
Tags Source
SHA-256 checksum
How to use checksums
a6c2f5329c5096c25ad56c148927da5c6ae8b557a4d6cf914a6ca35464a6de3e
BLAKE2b-256 checksum
How to use checksums
95678cfa42a22f5510d0096af092e4795e1aa55edbe25266ff1da70442c568d4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / docunext-0.2.0-py3-none-any.whl

Download URL docunext-0.2.0-py3-none-any.whl
Size 13.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ecd5e60064f4c5b2073666ea77bfa05109de067a3ff5ddecbe110e4a60218ba0
BLAKE2b-256 checksum
How to use checksums
7671725b157659c57a427d97f33ccdeb2d61171fe1fe4fffe6fb53e4176b0366
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for docunext 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for docunext-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page