Metadata-Version: 2.4
Name: acumatica-api
Version: 0.1.0
Summary: A lightweight Python SDK for the Acumatica contract-based REST API, built with `httpx2`.
Requires-Python: >=3.14
Description-Content-Type: text/markdown
Requires-Dist: httpx2>=2.4.0
Requires-Dist: tenacity>=9.1.4

# Acumatica

A lightweight Python SDK for the [Acumatica](https://www.acumatica.com) contract-based
REST API, built on [`httpx`](https://www.python-httpx.org/).

Read-only. The ODS mirrors the ERP rather than driving it, and a contract-based `PUT`
creates as well as updates, so write support waits until something needs it.

## Installation

```bash
uv add acumatica-api
```

## Requirements

- Python 3.14+

## Quick Start

```python
from acumatica import Acumatica

with Acumatica(
    "https://example.acumatica.com",
    client_id="11111111-2222-3333-4444-555555555555@MyTenant",
    client_secret="...",
    username="ods",
    password="...",
) as client:
    item = client.entity("StockItem").get("127-004033-001")
    print(item["Descr"]["value"])
```

## Authentication

Resource Owner Password Credentials, which is the only headless flow you can actually
register. The identity server advertises `client_credentials`, but Connected
Applications (SM303010) offers only Authorization Code, Implicit, ROPC and Hybrid.

**The tenant lives in the client ID**, not in a separate parameter. The ID issued at
registration ends in `@Tenant`, and that is what scopes the session.

The client requests the `api` and `offline_access` scopes, which means Acumatica reuses
a single session ID across the whole refresh chain. Pass a `TokenStore` so that chain
survives a cold start:

```python
from acumatica import Acumatica, TokenStore


class SecretsManagerTokenStore(TokenStore):
    def load(self) -> str | None: ...
    def save(self, refresh_token: str) -> None: ...


client = Acumatica(..., token_store=SecretsManagerTokenStore())
```

> **Refresh tokens are single-use and rotate, so a persisted one is mutable shared
> state.** If several workers cold-start and refresh from the same value, one wins and
> the rest get `invalid_grant` — and a loser writing its spent token back destroys the
> chain for everyone. Prefer a single refresher: one rate-limited queue consumer rather
> than a worker per webhook notification.

By default the whole chain expires 30 days after the *initial* authentication however
often it is redeemed, unless Sliding Expiration is configured for the application on
SM303010. The client falls back to the password grant when a refresh is refused, so
this recovers without a human — but it is worth turning the setting on.

## Endpoints

An endpoint is a contract, not a namespace, so a client is bound to one. Reading
manufacturing data alongside inventory means a second client:

```python
default = Acumatica(creds..., endpoint="Default", version="25.200.001")
mfg = Acumatica(
    creds...,
    endpoint="MANUFACTURING",
    version="25.100.001",
    limiter=default.limiter,
    session=default.session,
)
```

**Share the limiter and the session whenever a process holds more than one
client.** The budget is tenant-wide, so two clients each pacing to 100/min spend
200 against a cap of 150; and since both address the same instance with the same
credentials, a shared session is one token and one of the 20 API user slots rather
than two of each. `close()` ends what it was given, so close the borrower first or
let one owner do it.

**Pin the version and treat a bump as breaking.** `Default/26.200.001` is contract
version 5, which changes the query syntax (`$expand=Operations($expand=Material)`
rather than `Operations/Material`) *and* the data shape (a dropdown returns an ID and a
description rather than a plain value).

There are no named entity attributes, unlike the other SDKs in the house. Acumatica's
entity set belongs to the endpoint and can be extended per instance, so a list baked
into this package would be wrong somewhere. `acumatica.entities` holds the names proven
readable on the ADi instance; the authoritative check is per endpoint:

```
GET {base_url}/entity/{endpoint}/{version}/swagger.json
```

## Reading

```python
items = client.entity("StockItem")

items.get("127-004033-001")
items.get("SO", "000123")  # compound keys, in order
items.list(filter="ItemStatus eq 'Active'")  # one page
items.stream(page_size=200)  # every record
```

Payloads come back exactly as Acumatica sent them, so every scalar is wrapped in
`{"value": ...}`. Flatten them when you want to:

```python
from acumatica import unwrap

unwrap(items.get("127-004033-001"))  # {"InventoryID": "127-004033-001", ...}
```

`unwrap` leaves a field that carries anything besides `value` — such as the per-field
`error` contract version 5 adds — as a dict, because collapsing it would turn a
rejected field into a plausible-looking value.

### Incremental sync

```python
from datetime import UTC, datetime
from acumatica import modified_since

since = datetime(2026, 11, 17, 18, 24, 6, tzinfo=UTC)
for record in client.entity("StockItem").stream(filter=modified_since(since)):
    ...
```

Not every entity supports this. 129 of `Default`'s 735 schemas expose
`LastModifiedDateTime`; **`MANUFACTURING` exposes it on none of its 277**, and a
`$filter` on it there returns HTTP 500 rather than 400, so it reads like a server fault
rather than a bad field name. The underlying DACs do carry it, so it exists and is
simply unmapped — an endpoint extension surfaces it, and until then manufacturing
reconciles by full sweep.

## Two ways to get the wrong data with a 200

Both are closed by the client rather than left to callers, because neither produces an
error, a bad status, or a row count anything could compare against.

**A sub-second watermark drops rows.** Acumatica compares `LastModifiedDateTime`
against a value that can sit fractionally below the one it reported. `watermark` and
`modified_since` truncate to the whole second and back off by five minutes, so the
error direction is re-reading a row rather than missing one.

**An unqualified `$select` beside `$expand` silently empties the expansion.** The
collection comes back present and empty. Requesting it raises instead:

```python
items.list(select="InventoryID", expand="WarehouseDetails")
# ValueError: $select is set but names no field under the expanded
# 'WarehouseDetails'. Acumatica would answer 200 with 'WarehouseDetails' empty
# rather than failing.

items.list(
    select=["InventoryID", "WarehouseDetails/WarehouseID"],
    expand="WarehouseDetails",
)
```

## Rate limiting

Acumatica's licence caps three things, and the binding one is not the one that looks
binding. Measured on the TESTING tenant (tier M1 - Prime):

| constraint | value |
|---|---|
| Web Services API Users | 20 |
| Concurrent Web Services API Requests | 3 |
| Web Services API Requests per Minute | **150** |

150/min is 2.5 req/s, so three concurrent requests stay legal only above 1.2s mean
latency. Measured latencies run 0.40–1.76s, mean around 0.8s — so the rate binds and
the concurrency limit never does. Hence a token bucket, not a semaphore.

All three are tenant-wide and shared with every other integration on the instance,
which is why the client defaults to 100/min rather than 150. The budget covers token
requests too: the System Monitor counts `/identity/` alongside `/entity/`, `/api/`,
`/soap/` and `/Webhooks/`.

```python
client = Acumatica(..., requests_per_minute=100, burst=10)
```

The limiter is in-process. Several Lambda containers each holding their own can still
exceed the budget between them — that case needs a rate-limited queue consumer, which
is the same conclusion the refresh-token hazard reaches.

## Error Handling

```python
from acumatica import Acumatica, AcumaticaError

try:
    client.entity("StockItem").list()
except AcumaticaError as e:
    print(e.status_code)  # e.g. 403
    print(str(e))  # "Acumatica API error 403: Insufficient rights to screen IN202500"
```

A 403 names the form whose access right is missing, which is how the `ODS Integration`
role's grants were mapped. Timeouts, 429 and gateway statuses get three attempts in
total with exponential backoff; a 401 triggers one forced token refresh and one retry, then
gives up — a second 401 is a credentials problem, and retrying it burns rate budget and
risks the 20-slot API user limit.

## Version History

See [CHANGELOG.md](CHANGELOG.md).
