Metadata-Version: 2.4
Name: nutrient-dws
Version: 5.0.1
Summary: Nutrient DWS API client for the Processor, Data Extraction, and Accessibility APIs
License: MIT
License-File: LICENSE
Keywords: nutrient,dws,pdf,document,api,client,sdk,convert,ocr,redact,sign,data-extraction,accessibility
Author: PSPDFKit GmbH d/b/a Nutrient
Author-email: support@nutrient.io
Requires-Python: >=3.10,<4.0
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Provides-Extra: aiohttp
Requires-Dist: aiohttp (>=3.14.1,<4) ; (python_version >= "3.10") and (extra == "aiohttp")
Requires-Dist: httpx (>=0.21.2)
Requires-Dist: httpx-aiohttp (>=0.1.8,<0.2.0) ; (python_version >= "3.10") and (extra == "aiohttp")
Requires-Dist: pydantic (>=2.0.0)
Requires-Dist: pydantic-core (>=2.18.2,<3.0.0)
Requires-Dist: typing_extensions (>=4.0.0)
Project-URL: Documentation, https://www.nutrient.io/api/reference/public/
Project-URL: Homepage, https://www.nutrient.io/api/
Project-URL: Support, https://www.nutrient.io/support/request/
Description-Content-Type: text/markdown

# Nutrient Python Library

[![fern shield](https://img.shields.io/badge/%F0%9F%8C%BF-Built%20with%20Fern-brightgreen)](https://buildwithfern.com?utm_source=github&utm_medium=github&utm_campaign=readme&utm_source=Nutrient%2FPython)
[![pypi](https://img.shields.io/pypi/v/nutrient_dws)](https://pypi.python.org/pypi/nutrient_dws)

The Nutrient Python library provides convenient access to the Nutrient APIs from Python.

## Table of Contents

- [Installation](#installation)
- [Reference](#reference)
- [Usage](#usage)
- [Environments](#environments)
- [Async Client](#async-client)
- [Exception Handling](#exception-handling)
- [Advanced](#advanced)
  - [Access Raw Response Data](#access-raw-response-data)
  - [Retries](#retries)
  - [Timeouts](#timeouts)
  - [Custom Client](#custom-client)
- [Migrating from 3.x](#migrating-from-3x)
- [Support](#support)

## Installation

```sh
pip install nutrient_dws
```

## Reference

Each method's docstring describes its parameters and result. The
[DWS API reference](https://www.nutrient.io/api/reference/public/) documents every operation.

## Usage

The client groups the API by product: `client.processor`, `client.extraction`, `client.accessibility`,
`client.account`, and `client.tokens`.

```python
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.

```python
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.

```python
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">`.

```python
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.

```python
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.

```python
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.

```python
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.

```python
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.

```python
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:
- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout)
- [409](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409) (Conflict)
- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests)
- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) (All server errors, including 500)

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.

```python
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.

```python
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.

```python
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.

```python
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](https://www.nutrient.io/support/request/). The [DWS API reference](https://www.nutrient.io/api/reference/public/) documents every operation.

