Skip to main content

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

License

MIT

Metadata

Release files for docunext 0.1.1

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.1.1
File Size Uploaded Provenance Actions
docunext-0.1.1.tar.gz 14.5 kB With provenance Details for docunext-0.1.1.tar.gz

Built distribution (wheel)

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

Total release size: 27.7 kB

Release files / docunext-0.1.1.tar.gz

Download URL docunext-0.1.1.tar.gz
Size 14.5 kB
Tags Source
SHA-256 checksum
How to use checksums
3111fb4477156534b4c35939dd323aa173805f7260e4acaa26e95b8c8ce58c1f
BLAKE2b-256 checksum
How to use checksums
bb86c74b297a11cb184b16727397eb9da672bd324fdd84bb74ba64dbe4cdc380
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 25, 2026.

Transparency log

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

Download URL docunext-0.1.1-py3-none-any.whl
Size 13.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb3a9433771ac55c0c4da2fc3e2822ed5f0eeb52e014232f0b1edb60a5228dab
BLAKE2b-256 checksum
How to use checksums
87a9eddba682406a823a0f489ee731169162bb889ffa77358166ff4922c9dfd2
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 25, 2026.

Transparency log

Security for docunext 0.1.1

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.1.1.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 25, 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