Metadata-Version: 2.5
Name: exportflow
Version: 1.1.0
Summary: The official Python SDK for the ExportFlow document processing and verification API
Project-URL: Documentation, https://exportflow.app/developers
Project-URL: Changelog, https://exportflow.app/developers/changelog
Author: MeerTech Ltd
License: Proprietary
Keywords: documents,erp,exportflow,ocr,trade,verification
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.25
Description-Content-Type: text/markdown

# ExportFlow Python SDK

The official Python client for the ExportFlow API: upload trade documents from
your own software, have them classified and read, confirm what they say, and
verify them against each other.

```bash
pip install exportflow
```

Python 3.9 or later. The only dependency is `httpx`.

## Quick start

```python
from exportflow import ExportFlow

client = ExportFlow(api_key="exfk_test_...")   # or set EXPORTFLOW_API_KEY

# 1. Upload. The document is scanned, stored and queued for processing.
document = client.documents.upload(file="bill_of_lading.pdf")

# 2. Wait for processing (or use a webhook; see below).
document = client.documents.wait(document.id)
print(document.status, document.document_type)        # processed bill_of_lading

# 3. Read what was extracted.
extraction = client.documents.extraction(document.id)
print(extraction.as_dict())                           # {"bl_number": "MEDU7741203", ...}

# 4. Confirm what the documents say, then verify the shipment.
client.records.confirm(document.shipment_id, {"port_of_discharge": "NHAVA SHEVA"})
verification = client.verifications.create(document.shipment_id)
verification = client.verifications.wait(verification.id)
for finding in verification.findings:
    print(finding.severity, finding.message)
```

A key that begins `exfk_test_` works in the **sandbox**: the same pipeline,
separate data, never charged. A key that begins `exfk_live_` is **production**.
Create both in the developer console.

## How ExportFlow models documents

A **shipment** is a set of documents that travel together: a bill of lading, a
commercial invoice, a packing list, certificates. Documents are uploaded to a
shipment, each is **processed** (classified, then its fields extracted), and
the shipment is **verified** by checking the documents against each other and
against the published rule set.

**Documents are only checked against the other documents on the same
shipment.** `client.documents.upload(file=...)` with no `shipment_id` creates a
new shipment for that one document, so to verify several documents together,
create the shipment first and pass its id to every upload:

```python
shipment = client.shipments.create(
    reference="PO-7741",           # your own id
    origin_country="NG",           # ISO 3166-1 alpha-2
    destination_country="IN",
    destination_port="INNSA",      # UN/LOCODE: five characters, no space
    hs_code="180100",
)
for path in ("bl.pdf", "invoice.pdf", "packing_list.pdf"):
    client.documents.upload(file=path, shipment_id=shipment.id)
```

**A file holding several documents is split.** If one PDF contains, say, a
bill of lading and an invoice, the upload's status becomes `split` and each
part appears in `client.documents.list(shipment.id)` as a document of its own,
with `parent_document_id` naming the upload. Read and confirm the parts; the
`split` upload itself has no reading.

`document_type` is open text. Types with rules today are `bill_of_lading`,
`commercial_invoice`, `packing_list`, `certificate_of_origin`,
`phytosanitary_certificate` and `fpis_certificate`. Any other type is still
read and compared with the shipment's other documents.

### Why you confirm before you verify

Verification refuses to start (`ConflictError`, code `not_confirmed`) until the
shipment's record has been confirmed. This is deliberate. If a field was
misread, every finding computed from it would be wrong, in both directions.
Show your user what was read (`client.records.get(shipment_id)`), let them
confirm or correct it, and send that with `client.records.confirm(...)`.
Confirm what the document *says*, not what it should say: verification is what
finds the error.

Each field on the record lists every document's reading, with the `page` it
was read from, the `method` and a `confidence` from 0 to 1, so one call is
enough to build the confirmation screen. To confirm a field, send a value or,
when the documents do not give one, an absence reason:

```python
client.records.confirm(shipment_id, [
    {"name": "bl_number", "value": "MEDU7741203", "source_extraction_id": reading.extraction_id},
    {"name": "fpis_certificate_number", "absence_reason": "not_applicable"},
])
```

`absence_reason` is `not_applicable`, `missing_from_documents` or `illegible`.
The record returns it as `confirmed_absence`.

### Reading the result

`client.verifications.create(...)` returns at once with the verification's
`id` and `status="queued"`; it has no findings yet. Pass the id to
`client.verifications.wait(...)`, or wait for the `verification.completed`
webhook. Each finding's `severity` is one of:

| Severity | Meaning |
|---|---|
| `critical` | Will cause rejection |
| `verify` | Inconsistent, and may be intentional; a person should look |
| `clean` | A rule ran and passed |
| `uncovered` | No rule covers this. Not a pass |
| `unavailable` | A value the rule needed could not be read. Not a pass |

`verification.coverage` says what was checked: each document is `checked`
(rules for its type ran) or `cross_checked_only` (only compared with the other
documents, which is not a pass). Show `uncovered`, `unavailable` and
`cross_checked_only` differently from `clean`.

## Webhooks

Polling works; webhooks are better. Register an endpoint once:

```python
endpoint = client.webhook_endpoints.create(
    "https://erp.example.com/hooks/exportflow",
    event_types=["document.processing.completed", "verification.completed"],
)
print(endpoint.signing_secret)   # whsec_...  store this
```

Verify every delivery before trusting it:

```python
from exportflow import webhooks, SignatureVerificationError

def handle(request):
    try:
        event = webhooks.construct_event(
            payload=request.body,                               # raw bytes
            signature=request.headers["ExportFlow-Signature"],
            secret=WEBHOOK_SECRET,
        )
    except SignatureVerificationError:
        return 400
    if already_handled(event.id):          # deliveries are at-least-once
        return 200
    if event.type == "document.processing.completed":
        document_id = event.data["document"]["id"]
        ...
    return 200
```

Answer with any `2xx` within 10 seconds. Anything else is retried with
increasing delays for about two and a half hours. An event carries identifiers
and statuses, never document content: fetch the resource to read it.

| Event | When |
|---|---|
| `document.uploaded` | A document was accepted, scanned and stored |
| `document.processing.started` | Classification began |
| `document.processing.completed` | The document was classified and read |
| `document.processing.failed` | Processing stopped; `GET` the document for why |
| `verification.completed` | A verification finished; fetch it for the findings |
| `verification.failed` | A verification could not run |
| `usage.threshold.reached` | 80% or 100% of a monthly allowance was used |
| `billing.invoice.generated` | An invoice was issued to your organisation |
| `webhook.test` | You sent a test event from the developer console |

Every event's exact `data` is in the API reference (the OpenAPI document's
`webhooks` section): for documents, `document.id`, `shipment.id`, `status`
and `document_type`; for verifications, `verification.id`, `shipment.id`,
`status` and, on completion, a count of `findings` by severity. There are no
shipment events. During a secret rotation a delivery may carry two `v1=`
signatures; `construct_event` accepts either. A body that verifies but is not
a JSON object raises `InvalidWebhookPayloadError`, a subclass of
`SignatureVerificationError`.

## Errors

Every error is an `exportflow.ExportFlowError`. One returned by the API is an
`APIError` with a stable `code`, the HTTP `status_code` and a `request_id` to
quote to support. Branch on the type or the code, never on the message. Every
code, its status and what to do is listed in the
[error reference](https://exportflow.app/developers/docs/errors).

```python
import exportflow

try:
    client.verifications.create(shipment_id)
except exportflow.ConflictError as error:
    if error.code == "not_confirmed":
        ...                                   # ask the user to confirm the record
except exportflow.QuotaExceededError:
    ...                                       # the month's allowance is used up
except exportflow.RateLimitError as error:    # not raised for a spent quota
    time.sleep(error.retry_after or 5)
except exportflow.APIConnectionError:
    ...                                       # safe to retry later
```

| Exception | HTTP | Meaning |
|---|---|---|
| `AuthenticationError` | 401 | Key missing, wrong, revoked or expired |
| `PermissionDeniedError` | 403 | Missing scope, suspended account, network not allowed |
| `NotFoundError` | 404 | No such resource in this organisation and environment |
| `ConflictError` | 409 | Not possible in the current state (e.g. `not_confirmed`) |
| `InvalidRequestError` | 400, 422 | The request is wrong; do not retry |
| `RateLimitError` | 429 | Slow down; see `retry_after` |
| `QuotaExceededError` | 429 | Allowance or spending limit reached; not a `RateLimitError` |
| `SDKVersionUnsupportedError` | 426 | Upgrade this SDK |
| `ServerError` | 5xx | ExportFlow's fault; retried automatically |
| `APIConnectionError`, `APITimeoutError` | none | The API could not be reached |

## Retries and idempotency

The client retries connection failures, timeouts, `429 rate_limited`, `5xx`
and the two idempotency answers that mean "the same request, not yet"
(`request_in_progress`, `idempotency_conflict`) up to `max_retries` times
(default 2), with backoff, honouring `Retry-After`. When the API asks for a
longer wait than `max_retry_wait` (default 60 seconds), the error is raised at
once instead of blocking. `idempotency_key_reused` (the key was used for a
different request) is never retried: use a new key.

Every request that changes something carries an `Idempotency-Key`, and a retry
sends the *same* key and the *same* body, so the work is done once however many
times it is sent. To make your own retries safe across process restarts, pass
your own key:

```python
client.documents.upload(file="bl.pdf", shipment_id=sid, idempotency_key=f"upload-{erp_document_id}")
```

An upload retried with the same key sends exactly the same bytes, even from a
restarted process, so the API recognises it. Uploading the same file to the
same shipment twice returns the first document (`duplicate=True`) and is not
charged again.

Every object a call returns carries the `request_id` of that call, and
`client.last_request_id` holds the most recent one. Quote it to support.

## Usage and charges

```python
usage = client.usage.get()            # this month; or client.usage.get("2026-10")
for meter in usage.meters:
    print(meter.name, meter.succeeded, "of", meter.quota or "unlimited")
print(usage.estimated_charge, usage.currency)
```

Requests are not charged. Usage is recorded when work completes: a document
accepted, a document processed, a verification completed. Sandbox usage is
measured and never charged. Charges are estimates until an invoice is issued.

## Configuration

```python
ExportFlow(
    api_key=None,          # default: EXPORTFLOW_API_KEY
    base_url=None,         # default: EXPORTFLOW_BASE_URL or https://api.exportflow.app
    timeout=60.0,          # seconds per response
    max_retries=2,
    max_retry_wait=60.0,   # seconds; a longer Retry-After raises instead
    http_client=None,      # your own httpx.Client: proxies, TLS, tests
)
```

The client is safe to share between threads (read request ids from the
returned objects then, not from `last_request_id`). Use it as a context manager, or
call `close()`, to release its connections.

## Versioning

This SDK follows semantic versioning and speaks version 1 of the API. Within
version 1 the API only adds; nothing is removed or changed in meaning, so this
SDK keeps working as the API grows, and unknown fields are available on every
model's `.raw`. If the server ever reports a different major version the
client raises `IncompatibleAPIVersionError` rather than misread a response.
See the [changelog](https://exportflow.app/developers/docs/changelog).
