Nutrient Python Library
The Nutrient Python library provides convenient access to the Nutrient APIs from Python.
Table of Contents
- Installation
- Reference
- Usage
- Environments
- Async Client
- Exception Handling
- Advanced
- Migrating from 3.x
- Support
Installation
pip install nutrient_dws
Reference
Each method's docstring describes its parameters and result. The DWS API reference documents every operation.
Usage
The client groups the API by product: client.processor, client.extraction, client.accessibility,
client.account, and client.tokens.
from nutrient_dws import BuildInstructions, FilePart, NutrientClient
client = NutrientClient() # api_key defaults to the NUTRIENT_API_KEY environment variable
# Convert a Word document to PDF.
with open("report.docx", "rb") as document, open("report.pdf", "wb") as out:
for chunk in client.processor.convert_to_pdf(file=document):
out.write(chunk)
# Merge two documents with Build instructions.
with open("a.pdf", "rb") as first, open("b.docx", "rb") as second, open("merged.pdf", "wb") as out:
for chunk in client.processor.build(
instructions=BuildInstructions(parts=[FilePart(file="file1"), FilePart(file="file2")]),
file1=first,
file2=second,
):
out.write(chunk)
A file parameter takes the file's content: an open binary file, bytes, or a (filename, content) tuple. A
str is sent as the content itself, so open a path rather than passing it. Methods that return a file yield it in
chunks, and methods that return JSON return pydantic models. Request bodies are pydantic models too, all importable
from nutrient_dws.
Asynchronous Build jobs
A long Build can run in the background: with prefer="respond-async", DWS answers 202 Accepted with a job
instead of the file. Read that answer through the raw client, wait for the job, then download its result. The job
token authorizes only that job.
import json
import time
import uuid
from nutrient_dws import BuildInstructions, FilePart, NutrientClient
client = NutrientClient()
with open("document.pdf", "rb") as document, client.processor.with_raw_response.build(
instructions=BuildInstructions(parts=[FilePart(file="file1")]),
file1=document,
prefer="respond-async",
idempotency_key=str(uuid.uuid4()), # sending the same key again returns the same job
) as response:
job = json.loads(b"".join(response.data))["data"] # {"job_id": ..., "job_access_token": ..., ...}
token = job["job_access_token"]
status = client.processor.jobs.get(job["job_id"], async_job_token=token).data
while status.status in ("not_started", "in_progress"):
time.sleep(10)
status = client.processor.jobs.get(job["job_id"], async_job_token=token).data
if status.status != "completed":
raise RuntimeError(f"The Build job ended {status.status}: {status.error}")
with open("result.pdf", "wb") as output:
for chunk in client.processor.jobs.get_result(job["job_id"], async_job_token=token):
output.write(chunk)
Build outputs
Build returns a PDF unless the instructions name another output: PDF/A, images, Office documents, or the
document's text and tables as JSON.
import json
from nutrient_dws import (
BuildInstructions,
BuildOutput,
FilePart,
ImageOutput,
JsonContentOutput,
NutrientClient,
OfficeOutput,
Part,
PdfaOutput,
)
client = NutrientClient()
parts: list[Part] = [FilePart(file="file1")]
outputs: dict[str, BuildOutput] = {
"archived.pdf": PdfaOutput(type="pdfa", conformance="pdfa-2b"),
"page.png": ImageOutput(type="image", format="png", dpi=150),
"document.docx": OfficeOutput(type="docx"),
}
for name, output in outputs.items():
with open("document.pdf", "rb") as document, open(name, "wb") as result:
for chunk in client.processor.build(instructions=BuildInstructions(parts=parts, output=output), file1=document):
result.write(chunk)
# JSON content: the text and tables of every page.
text = JsonContentOutput(type="json-content", plain_text=True, tables=True)
with open("document.pdf", "rb") as document:
content = json.loads(
b"".join(client.processor.build(instructions=BuildInstructions(parts=parts, output=text), file1=document))
)
print(content["pages"][0]["plainText"])
HTML assets and image watermarks
The convenience methods upload one file each. For HTML that needs its stylesheets, images, or fonts, or for an image
watermark, use processor.build: upload the extra files as file2, file3, and so on, and refer to them by that
name. An HTML page imports its assets by those names, for example <link rel="stylesheet" href="file2">.
from nutrient_dws import BuildInstructions, FilePart, HtmlPart, ImageWatermarkAction, NutrientClient
client = NutrientClient()
with open("page.html", "rb") as html, open("style.css", "rb") as css, open("page.pdf", "wb") as output:
for chunk in client.processor.build(
instructions=BuildInstructions(parts=[HtmlPart(html="file1", assets=["file2"])]),
file1=html,
file2=css,
):
output.write(chunk)
quarter = {"value": 25, "unit": "%"} # or a number of points, such as 200
logo_watermark = ImageWatermarkAction.model_validate(
{"type": "watermark", "image": "file2", "width": quarter, "height": quarter, "opacity": 0.5}
)
with open("document.pdf", "rb") as document, open("logo.png", "rb") as logo, open("watermarked.pdf", "wb") as output:
for chunk in client.processor.build(
instructions=BuildInstructions(parts=[FilePart(file="file1")], actions=[logo_watermark]),
file1=document,
file2=logo,
):
output.write(chunk)
Batches
A batch runs one Data Extraction operation over up to ten documents. Each document becomes a stored run; read its result once the batch is done.
import json
import time
from nutrient_dws import NutrientClient
client = NutrientClient()
with open("invoice.pdf", "rb") as first, open("document.pdf", "rb") as second:
batch = client.extraction.batches.submit(operation="parse", instructions={"mode": "text"}, files=[first, second])
while batch.status not in ("done", "error", "canceled"):
time.sleep(5)
batch = client.extraction.batches.get(batch.id)
for document in batch.documents:
# After `error`, a document can still be running: check each one's status.
if document.result_available and document.run_id:
result = json.loads(b"".join(client.extraction.runs.download_asset(document.run_id, "result")))
print(document.file_name, document.status, list(result))
else:
print(document.file_name, document.status, document.error)
Environments
This SDK allows you to configure different environments for API requests.
from nutrient_dws import NutrientClient
from nutrient_dws.environment import NutrientClientEnvironment
client = NutrientClient(
environment=NutrientClientEnvironment.DEFAULT,
)
Async Client
AsyncNutrientClient has the same methods for asyncio. If you pass your own httpx_client, make it an
httpx.AsyncClient() and set its timeout.
import asyncio
from nutrient_dws import AsyncNutrientClient
client = AsyncNutrientClient()
async def main() -> None:
with open("report.docx", "rb") as document, open("report.pdf", "wb") as out:
async for chunk in client.processor.convert_to_pdf(file=document):
out.write(chunk)
asyncio.run(main())
Exception Handling
When the API returns a non-success status code (4xx or 5xx response), a subclass of the following error will be thrown.
from nutrient_dws.core.api_error import ApiError
try:
# A method that returns a file sends its request when you read the file, so read it inside `try`.
with open("document.pdf", "wb") as output:
for chunk in client.processor.convert_to_pdf_json(url="https://www.example.com/document.docx"):
output.write(chunk)
except ApiError as e:
print(e.status_code)
print(e.body)
Advanced
Access Raw Response Data
The SDK provides access to raw response data, including headers, through the .with_raw_response property.
The .with_raw_response property returns a "raw" client that can be used to access the .headers and .data attributes.
from nutrient_dws import NutrientClient
client = NutrientClient(...)
# A method that returns JSON: `.data` is the parsed result.
response = client.extraction.with_raw_response.parse_json(url="https://www.example.com/invoice.pdf")
print(response.headers["x-request-id"]) # access the response headers
print(response.status_code) # access the response status code
print(response.data.output.markdown) # access the underlying object
# A method that returns a file: open its raw response with `with`, and read `.data` inside it.
with client.processor.with_raw_response.convert_to_pdf_json(
url="https://www.example.com/document.docx"
) as response:
print(response.headers["content-type"])
with open("document.pdf", "wb") as output:
for chunk in response.data:
output.write(chunk)
Retries
The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).
It retries these status codes:
Methods that return a file (an iterator of bytes) make a single attempt, and max_retries does not apply to them: retry them yourself if you need to.
Use the max_retries request option to configure this behavior.
client.extraction.parse_json(url="https://www.example.com/invoice.pdf", request_options={
"max_retries": 1
})
Timeouts
The SDK defaults to a 660 second timeout, just past the 10 minutes DWS allows a synchronous request. You can configure this with a timeout option at the client or request level. A custom httpx_client keeps its own timeout, so set one on it.
from nutrient_dws import NutrientClient
client = NutrientClient(..., timeout=20.0)
# Override timeout for a specific method
client.extraction.parse_json(url="https://www.example.com/invoice.pdf", request_options={
"timeout": 120
})
Custom Client
You can override the httpx client to customize it for your use-case. Some common use-cases include support for proxies
and transports.
import httpx
from nutrient_dws import NutrientClient
client = NutrientClient(
...,
httpx_client=httpx.Client(
timeout=660.0, # a custom client keeps its own timeout
proxy="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)
Migrating from 3.x
Version 4 is built with a new generator and follows the DWS API reference.
It replaces the 3.x client and its convenience methods: each 3.x call becomes a call to the
endpoint it used, mostly client.processor.build with Build instructions. NutrientClient is synchronous;
AsyncNutrientClient has the same methods for asyncio. Python 3.10 or newer is required.
from nutrient_dws import BuildInstructions, FilePart, NutrientClient
client = NutrientClient() # api_key defaults to the NUTRIENT_API_KEY environment variable
# 3.x: await client.merge(["a.pdf", "b.docx"])
with open("a.pdf", "rb") as first, open("b.docx", "rb") as second, open("merged.pdf", "wb") as out:
for chunk in client.processor.build(
instructions=BuildInstructions(parts=[FilePart(file="file1"), FilePart(file="file2")]),
file1=first,
file2=second,
):
out.write(chunk)
| 3.x | 4.0 |
|---|---|
NutrientClient(api_key, base_url=None, timeout=None), await client.… |
NutrientClient(api_key=..., base_url=..., timeout=..., max_retries=...) (synchronous) or AsyncNutrientClient(...). api_key falls back to the NUTRIENT_API_KEY environment variable. |
A path or URL as the file ("a.pdf") |
The file's content: open("a.pdf", "rb"), bytes, or a (filename, content) tuple. A str is sent as the content itself. For a URL, use the method's *_json variant where it has one. |
extract_api_key |
Not available. With a global DWS API key, one client covers every API; with a separate Data Extraction key, create a second client for client.extraction. |
workflow(), add_file_part, apply_action(s), output_*, execute |
processor.build(instructions=BuildInstructions(...), file1=..., … file10=...): the instructions are the builder's result. Reference uploaded files by field name (FilePart(file="file1")); for URLs, use processor.build_json(parts=..., actions=..., output=...). |
dry_run() |
processor.analyze_build(parts=..., actions=..., output=...) |
convert(file, "pdf") |
processor.convert_to_pdf(file=...) (Office, images, email), processor.generate_pdf(html=...), processor.markdown_to_pdf(markdown=...). Other formats: processor.build with an output. |
merge, rotate, flatten, optimize, password_protect, set_metadata, set_page_labels, add_page, duplicate_pages, delete_pages, split |
processor.build with the matching parts, actions, and output. |
ocr(file, language) |
processor.ocr(file=..., data=OcrProcessorRequestData(language=...)) |
watermark_text, watermark_image |
processor.watermark(file=..., data=...) |
create_redactions_text/regex/preset, apply_redactions |
processor.redact(file=..., data=...) |
create_redactions_ai |
processor.ai_redact(file=..., data=...) |
apply_instant_json, apply_xfdf |
processor.build with the applyInstantJson / applyXfdf action. |
extract_text, extract_table, extract_key_value_pairs |
processor.build with a json-content output. |
sign(pdf, data, options) |
processor.sign(file=..., data=..., image=..., graphic_image=...) |
parse(file, mode, output_format) |
extraction.parse(file=..., instructions=...); extraction.parse_json(url=..., ...) for URLs. |
create_token, delete_token |
tokens.create(...), tokens.revoke(...) |
get_account_info() |
account.get_info(); account.get_usage(product=...) is new. |
Result dicts {"buffer", "mimeType", "filename"} |
File responses are iterators of byte chunks; JSON responses are pydantic models. |
NutrientError, ValidationError, APIError, AuthenticationError, NetworkError |
nutrient_dws.core.ApiError (with status_code and body) and one subclass per documented status, such as nutrient_dws.UnauthorizedError. |
Support
Ask questions and report problems through Nutrient support. The DWS API reference documents every operation.
Metadata
Release files for nutrient-dws 5.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| nutrient_dws-5.0.0.tar.gz | 278.5 kB | Without provenance | Details for nutrient_dws-5.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| nutrient_dws-5.0.0-py3-none-any.whl | Python 3 | none | any | Details for nutrient_dws-5.0.0-py3-none-any.whl |
Total release size: 912.3 kB
Release files / nutrient_dws-5.0.0.tar.gz
| Download URL | nutrient_dws-5.0.0.tar.gz |
|---|---|
| Size | 278.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c038ba9259696f6d4d6ee7938a47669b5d3a5389a7acace58932ae827f127dc9
|
|
BLAKE2b-256 checksum How to use checksums |
cd675b7f7ac2dc071bc786e31c995a207189abdab0fa6d35def3aae2aacea6ab
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / nutrient_dws-5.0.0-py3-none-any.whl
| Download URL | nutrient_dws-5.0.0-py3-none-any.whl |
|---|---|
| Size | 633.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7b32a6a642a630c3c5d63b9d24d4cf718dc713b6266281ef292f7b75fdadb944
|
|
BLAKE2b-256 checksum How to use checksums |
33cab0441bfa2df209d9289f48c164d586c475d8e368f80592a3cbe3470caeb2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for nutrient-dws 5.0.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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.