Metadata-Version: 2.4
Name: acumatica-api
Version: 0.2.1
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/).

## 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.

### Closing signs out, and you want it to

**Acumatica holds a session for an hour after a password grant, and the
concurrent-login cap is per user** — `Max. Number of Concurrent Logins` on Users
(SM201010), which overrides the User Types (EP202500) limit. A short-lived process
that grants and exits leaves its session held, so a handful of runs in quick
succession exhaust the account. The next grant is refused with an HTTP 500 carrying
an IIS HTML page whose `<title>` holds the real diagnosis; nothing about it resembles
a licence error. This was found the hard way, by exhausting it.

So `close()` signs out — including on `__exit__`, which is why the context manager is
the right way to use the client:

```python
with Acumatica(...) as client:
    ...
# signed out here
```

The default signs out only when the refresh chain is **not** persisted. A stored chain
is meant to be resumed on the next cold start, and signing out would discard the
session the `TokenStore` exists to keep. Override with `sign_out_on_close=True` or
`False` when you want to decide for yourself. A session borrowed from another client
is never signed out, since it belongs to the client that created it.

## 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.

## Writing

**Acumatica has no create verb.** `PUT /{Entity}` is an upsert: it creates when the
key fields match nothing and updates when they match something. So an update whose key
is wrong or missing silently becomes a *new record*, answering 200 with a body that
looks exactly like a successful update — and on an auto-numbered entity it won't even
look wrong.

`create` and `update` send the conditional headers that turn that into an HTTP 412, so
each says which operation it means and fails when the record disagrees:

```python
items = client.entity("StockItem")
body = {"InventoryID": {"value": "ITEM1"}, "Descr": {"value": "A thing"}}

items.create(body)  # If-None-Match: *  — 412 if it already exists
items.update(body)  # If-Match: *       — 412 if it doesn't
items.put(body)  # upsert, named for the verb rather than an intent
items.patch({"Descr": {"value": "New"}}, filter="InventoryID eq 'ITEM1'")
items.delete("ITEM1")
```

Both headers were checked against a live instance rather than assumed, each with a
control that isolates the header from the payload. `If-None-Match` is the awkward one
to prove: on an auto-numbering entity a supplied key is ignored, so every create
succeeds with a fresh id and there is never a collision to refuse. Letting the ERP
assign an id and creating again with *that* id is the test, and it comes back 412.

**On an auto-numbered entity, the id you sent is not the id that was created.** Read it
out of the response, or diff the key list before and after. Deleting the key you
supplied deletes the wrong record — or nothing, while the real ones accumulate.

Bodies go out in the same `{"value": ...}` envelope they come back in. `PATCH` never
creates, so it needs no guard — a key matching nothing is a 404. Prefer it where the
contract offers it; 119 of CV4's paths accept `PATCH` against 238 that accept `PUT`.

Errors worth catching separately: `AcumaticaPreconditionError` (412 — the guard fired),
`AcumaticaConflictError` (409 — changed underneath you). A 422 is a validation failure
and arrives as a plain `AcumaticaError` carrying the ERP's message.

### Retries differ between reads and writes

A read costs rate budget to repeat. **A write that reached the ERP is a record**, and
no status code tells you whether an ambiguous failure got there.

| | reads | writes |
|---|---|---|
| timeout | retried | **raised** |
| 429 | retried | retried |
| 502 / 503 / 504 | retried | **raised** |

429 means the request was refused *before* processing, so nothing was applied and
repeating it is free. Everything else that looks transient leaves open that the ERP
acted and the answer was lost coming back — and repeating a `create` whose number
Acumatica generates would make a second record.

Those ambiguous failures raise **`AcumaticaUncertainWriteError`**, which is an
`AcumaticaError` so a plain `except AcumaticaError` around a write catches it. Don't
retry it blind — read the record back by its key, which is cheap and is the only thing
that answers the question:

```python
try:
    items.create(body)
except AcumaticaUncertainWriteError:
    # It may or may not be there. Go and look.
    existing = items.list(filter="InventoryID eq 'ITEM1'")
```

A throttle backs off on the scale of the window that rejected it — 20s, doubling,
capped at 60s — and honours `Retry-After` when the server sends one. The 2s used for a
gateway blip would land back inside the same minute and be refused again.

**`patch` is the one write with no structural guard**, and that's a real limit rather
than an oversight: the record is identified by `filter` or by key fields inside the
body, and nothing here knows which of an entity's fields are its keys. It's the mildest
of the hazards, since `PATCH` cannot create — the failure is an error or the wrong
record, never a silent duplicate. Pass `filter` when the keys aren't in the body.

### 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`; **the stock `MANUFACTURING` contract exposes it on none of its
277**. The underlying DACs do carry it, so it exists and is simply unmapped — and an
endpoint extension surfaces it. On the ADi instance one already does:
`ODS_MANUFACTURING/25.100.001` is byte-for-byte the stock manufacturing contract apart
from a single added field, `ProductionOrder.LastModifiedDateTime`, and filtering on it
there works. So "manufacturing can only be swept in full" is a statement about a
contract, not about the ERP — though it remains true of every entity nobody has
extended, which is all of them but one.

Two caveats, both measured:

- **A watermark can be filterable without being readable.** That same field is absent
  from the response payload entirely, and an explicit `$select` naming it returns 200
  and still omits it. Sync from your own clock.
- **Two HTTP 500s look identical and mean opposite things.** `"The DateTime type cannot
  be used in the $filter value"` means your literal syntax is wrong — use
  `datetimeoffset'...'`, which `watermark()` emits — and the field is fine.
  `"The given key was not present in the dictionary"` means the field is not mapped on
  that endpoint. Both are 500 rather than 400, so neither reads as a client error.

## 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** |

The rate is what binds. Neither of the other two behaves like a cap — a width sweep
against TESTING put **seven requests in flight with zero refusals**, so the licensed
"3 concurrent" is not enforced as a refusal. Hence a token bucket, not a semaphore.

**Concurrency is worth having, but it saturates fast**, and it is worth knowing where:

| workers | req/min | mean in flight | vs 1 worker |
|---|---|---|---|
| 1 | 121 | 1.00 | 1.00x |
| 2 | 145 | 1.98 | 1.19x |
| 3 | 165 | 2.92 | 1.36x |
| 4 | 192 | 3.78 | 1.58x |
| 6 | 203 | 5.69 | **1.67x** |
| 8 | 173 | 7.13 | 1.43x |

Throughput peaks near six and *degrades* beyond it, while median latency climbs from
0.48s to 2.34s. So about 1.6x is the whole return — page size is the bigger lever,
because it divides the request count outright instead of competing for the same
tenant-wide budget.

**Sustained load is shaped; short bursts are not.** The faster rows above clear
150/min — but each run is only 14–24s, too short to drain a per-minute budget. Held
longer it is pulled back: 402 requests over 172s averaged ~140/min with zero refusals,
opening near 155/min and sagging to ~130, while median latency rose from 0.34s unloaded
to 1.40s. So treat any benchmark shorter than the budget window as measuring burst
capacity, not throughput. A 429 exists — no `Retry-After`, non-JSON body — but took 24
workers to provoke. **The failure mode to design for is latency, not refusal**: a
client waiting for a 429 to back off will never see one, it will just get slower.

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).
