# Python
Source: https://www.desktopaccountingapi.com/docs/sdks/python/

> Install and use the Desktop Accounting API Python SDK, with typed models, Decimal money, auto-pagination, typed errors and safe retries.

```sh
pip install desktopaccountingapi-quickbooks-desktop==0.12.1
```

Requires Python 3.9 or newer. The distribution is `desktopaccountingapi-quickbooks-desktop`; the import package is `desktopaccountingapi`. It depends on `httpx` and `typing_extensions`, is fully typed and checks clean under `mypy --strict`.

## Create a client

```python
import os
from desktopaccountingapi import DesktopAccountingApi

client = DesktopAccountingApi(
    api_key=os.environ["DAAPI_SECRET_KEY"],  # the default, so optional
    timeout=100.0,  # seconds
    max_retries=2,
)

qb = client.for_end_user("eu_01j9x4m6v4c8k2t7q0r5s3w1zb")
```

## Make calls

Methods take keyword arguments in `snake_case`; responses are typed models with `snake_case` attributes.

```python
from datetime import date
from decimal import Decimal
from desktopaccountingapi import DesktopAccountingApi
from desktopaccountingapi.types import InvoiceLineCreateInput

qb = DesktopAccountingApi().for_end_user("eu_01j9...")

customer = qb.qbd.customers.create(name="Northwind Traders", email="ap@northwind.example")

invoice = qb.qbd.invoices.create(
    customer_id=customer.id,
    transaction_date=date(2026, 10, 5),
    lines=[InvoiceLineCreateInput(item_id="80000003-1730311000", quantity=2, rate=Decimal("125.00"))],
)

qb.qbd.invoices.update(invoice.id, revision_number=invoice.revision_number, memo="Thanks for your order")
```

Money is `decimal.Decimal` in both directions, so amounts are exact. Omit an argument to leave a field out; pass `None` to send `null` and clear a clearable field.

Per-call options are keyword arguments: `end_user_id=`, `idempotency_key=` on writes, `timeout=` (per attempt) and `total_timeout=` (the whole call). The async client enforces `total_timeout` as a hard bound; the sync client enforces it between network operations, so one stalled read can overrun it by at most its read budget and a server trickling header bytes can extend an attempt. The SDK never starts its own attempt or retry after the deadline, but retries inside an injected transport, synchronous DNS lookups and your own auth, hook or transport code are not bounded, and a transport error that arrives late surfaces as `APIConnectionError`. Use the async client when you need a hard bound.

## Pagination

```python
from desktopaccountingapi import DesktopAccountingApi

qb = DesktopAccountingApi().for_end_user("eu_01j9...")

for invoice in qb.qbd.invoices.list(updated_after="2026-10-01"):
    print(invoice.ref_number, invoice.subtotal)

for page in qb.qbd.customers.list(limit=100).iter_pages():
    print(len(page.data), page.has_more, page.cursor_expires_at)

vendors = qb.qbd.vendors.list().list_all()
```

Fast item loops request the next page when they reach it. If you keep requesting items after holding a page for more than two seconds, the iterator can fetch the next page early to reduce cursor expiry. A later `break` can leave that page unused. Page-by-page iteration fetches a page only when requested, so fetch the next page promptly. Read-ahead cannot keep a cursor alive while your code pauses indefinitely. If the cursor expires, the pager raises `CursorExpiredError` with `items_yielded`, `pages_served`, `last_id`, `last_updated_at` and `reason`, and does not restart the list. See [Pagination](https://www.desktopaccountingapi.com/docs/guides/pagination/).

## Errors

All API errors derive from `APIError`: `InvalidRequestError`, `AuthenticationError`, `PermissionDeniedError`, `BillingError`, `RateLimitError`, `IntegrationConnectionError`, `IntegrationError`, `OutcomeUnknownError`, `InternalError`, `CursorExpiredError` and `ResultUnavailableError` (the result is no longer available: never send an applied write again, read the object instead; a read is safe to send again). `APIConnectionError` means no response arrived. `RequestPendingError` means the SDK stopped waiting for a request that reached QuickBooks: the client timeout ended, or checking on it failed (the failed check says nothing about the write). It carries `request_id`, `timeout_error` and `idempotency_key`; resend a write only with that key. Every error of a write carries `idempotency_key`.

```python
from desktopaccountingapi import APIError, DesktopAccountingApi, IntegrationConnectionError

qb = DesktopAccountingApi().for_end_user("eu_01j9...")
try:
    qb.qbd.health_check()
except IntegrationConnectionError as err:
    print(err.user_facing_message)
except APIError as err:
    print(err.code, err.request_id, err.message)
```

Each error exposes `code`, `type`, `message`, `user_facing_message`, `http_status_code`, `integration_code`, `request_id`, `retryable`, `outcome`, `param` and `details`. See [Error handling](https://www.desktopaccountingapi.com/docs/guides/error-handling/).

Errors from an HTTP response are also an `APIStatusError` and, for their status, a `BadRequestError` (400), `NotFoundError` (404), `ConflictError` (409), `UnprocessableEntityError` (422) or `InternalServerError` (5xx), so `except NotFoundError:` works next to `except InvalidRequestError:`.

## Idempotency and retries

Writes get an idempotency key automatically and reuse it across retries. Pass `idempotency_key=` to tie a write to your own record. See [Idempotency](https://www.desktopaccountingapi.com/docs/guides/idempotency/).

## asyncio client

`AsyncDesktopAccountingApi` has the same methods as coroutines, for `asyncio` applications:

```python
from desktopaccountingapi import AsyncDesktopAccountingApi

async def main() -> None:
    qb = AsyncDesktopAccountingApi().for_end_user("eu_01j9...")
    async for invoice in qb.qbd.invoices.list(limit=50):
        print(invoice.ref_number)
```

Pass your own `httpx.Client` (`httpx.AsyncClient` for the async client) as `http_client=` for proxies or custom transports.

## Async requests

`enqueue` queues a request without waiting and returns a request handle:

```python
from decimal import Decimal
from desktopaccountingapi import DesktopAccountingApi
from desktopaccountingapi.types import InvoiceLineCreateInput

qb = DesktopAccountingApi().for_end_user("eu_01j9...")

handle = qb.qbd.invoices.enqueue.create(
    customer_id="80000001-1730311000",
    lines=[InvoiceLineCreateInput(item_id="80000003-1730311000", quantity=2, rate=Decimal("125.00"))],
    queue_ttl=3600,
)
print(handle.id)  # req_...
invoice = handle.wait(timeout=120)  # long-polls until QuickBooks answers
print(invoice.ref_number)
```

`handle.status()` reads the request once, and `handle.result()` returns the result if the request has finished or raises `RequestPendingError` if it has not. A write the API [recovered](https://www.desktopaccountingapi.com/docs/guides/request-lifecycle/#recovered-writes) without its result raises `ResultUnavailableError` from `wait()` and `result()`: do not send it again; retrieve the object by `error.recovered_object_id`.

## Raw responses

```python
from desktopaccountingapi import DesktopAccountingApi

qb = DesktopAccountingApi().for_end_user("eu_01j9...")

raw = qb.qbd.customers.with_raw_response.retrieve("80000001-1730311000")
print(raw.status_code, raw.request_id, raw.headers.get("daapi-warnings"))
customer = raw.parse()
```

## Webhooks

```python
import os
from desktopaccountingapi import WebhookVerificationError, webhooks

def handle_webhook(raw_body: bytes, headers: dict[str, str]) -> int:
    try:
        event = webhooks.verify(raw_body, headers, os.environ["DAAPI_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return 400
    print(event.type, event.data.get("id"))
    return 204
```

`verify` checks the signature and the timestamp (within 300 seconds) against the raw body and returns a `WebhookEvent`. It needs no API key; `client.webhooks.verify(...)` is the same helper on a client.

## Porting from Conductor

Code written for `conductor-py` runs after you change the import and the API key, pass the new `eu_...` end-user IDs, and make the changes listed below the example. Keys, end users and customer reconnection come first; see [Migrating from Conductor](https://www.desktopaccountingapi.com/docs/get-started/migrating-from-conductor/).

```python
# Before:
#   import conductor
#   from conductor import Conductor
#   client = Conductor(api_key=os.environ["CONDUCTOR_SECRET_KEY"])
import os

import desktopaccountingapi as conductor
from desktopaccountingapi import DesktopAccountingApi as Conductor

client = Conductor(api_key=os.environ["DAAPI_SECRET_KEY"])

# Unchanged Conductor code:
for invoice in client.qbd.invoices.list(conductor_end_user_id="eu_01j9...", limit=50):
    print(invoice.ref_number)
try:
    client.qbd.invoices.retrieve("1A4F-1730312567", conductor_end_user_id="eu_01j9...")
except conductor.NotFoundError:
    print("No such invoice")
except conductor.APIStatusError as e:
    print(e.status_code, getattr(e, "code", None), getattr(e, "user_facing_message", str(e)))
```

- `conductor_end_user_id=` is accepted on every QuickBooks Desktop method and sent as `Daapi-End-User-Id`. Passing a different `end_user_id=` too raises `DaapiError`.
- `api_key`, `base_url`, `timeout` (seconds per attempt), `max_retries`, `default_headers` and `http_client` keep their names. A base URL ending in `/v1` works. `DAAPI_LOG` plays the part of `CONDUCTOR_LOG`.
- `ConductorError`, `APIError`, `APIStatusError`, `APIConnectionError`, `APITimeoutError` and the status classes exist under Conductor's names; `status_code`, `body`, `code` and `user_facing_message` are on every API error, next to `cause`, `fixes`, `docs_url` and `outcome`.
- Replace `page.has_next_page()` / `get_next_page()` loops with `iter_pages()`. `extra_headers`, `extra_query` and `extra_body` are not supported.
