acumatica-api 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- acumatica/__init__.py +20 -0
- acumatica/auth.py +318 -0
- acumatica/client.py +284 -0
- acumatica/endpoints/__init__.py +0 -0
- acumatica/endpoints/base.py +191 -0
- acumatica/entities.py +88 -0
- acumatica/errors.py +21 -0
- acumatica/ratelimit.py +106 -0
- acumatica/utils.py +206 -0
- acumatica_api-0.1.0.dist-info/METADATA +232 -0
- acumatica_api-0.1.0.dist-info/RECORD +13 -0
- acumatica_api-0.1.0.dist-info/WHEEL +5 -0
- acumatica_api-0.1.0.dist-info/top_level.txt +1 -0
acumatica/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. include:: ../README.md
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from acumatica.auth import AcumaticaAuthError as AcumaticaAuthError
|
|
6
|
+
from acumatica.auth import MemoryTokenStore as MemoryTokenStore
|
|
7
|
+
from acumatica.auth import TokenStore as TokenStore
|
|
8
|
+
from acumatica.client import DEFAULT_ENDPOINT as DEFAULT_ENDPOINT
|
|
9
|
+
from acumatica.client import DEFAULT_VERSION as DEFAULT_VERSION
|
|
10
|
+
from acumatica.client import Acumatica as Acumatica
|
|
11
|
+
from acumatica.endpoints.base import DEFAULT_PAGE_SIZE as DEFAULT_PAGE_SIZE
|
|
12
|
+
from acumatica.endpoints.base import Entity as Entity
|
|
13
|
+
from acumatica.entities import DEFAULT_ENTITIES as DEFAULT_ENTITIES
|
|
14
|
+
from acumatica.entities import MANUFACTURING_ENTITIES as MANUFACTURING_ENTITIES
|
|
15
|
+
from acumatica.errors import AcumaticaError as AcumaticaError
|
|
16
|
+
from acumatica.errors import AcumaticaRetryableError as AcumaticaRetryableError
|
|
17
|
+
from acumatica.ratelimit import RateLimiter as RateLimiter
|
|
18
|
+
from acumatica.utils import modified_since as modified_since
|
|
19
|
+
from acumatica.utils import unwrap as unwrap
|
|
20
|
+
from acumatica.utils import watermark as watermark
|
acumatica/auth.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""OAuth 2.0 against Acumatica's identity endpoint.
|
|
2
|
+
|
|
3
|
+
Acumatica's identity server advertises `client_credentials`, but the Connected
|
|
4
|
+
Applications (SM303010) form offers only Authorization Code, Implicit, Resource
|
|
5
|
+
Owner Password Credentials and Hybrid. Advertised at the protocol level is not
|
|
6
|
+
the same as registrable, so ROPC is the only headless flow available.
|
|
7
|
+
|
|
8
|
+
Measured on the TESTING instance, 2026-11-17:
|
|
9
|
+
|
|
10
|
+
- `expires_in` is exactly 3600 with no grace: HTTP 200 at 55 minutes, 401 at 60.
|
|
11
|
+
- The refresh chain survives a long idle -- a refresh redeemed after the access
|
|
12
|
+
token had been dead for 20 minutes returned a new pair and worked.
|
|
13
|
+
- Refresh tokens are single-use and rotate; replaying a spent one returns
|
|
14
|
+
`invalid_grant`.
|
|
15
|
+
|
|
16
|
+
With the `api` and `offline_access` scopes Acumatica reuses one session ID
|
|
17
|
+
across the whole refresh chain, so a persisted refresh token means a cold start
|
|
18
|
+
resumes the existing session rather than consuming another of the 20 API user
|
|
19
|
+
slots -- and no sign-out is required.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from datetime import UTC, datetime, timedelta
|
|
25
|
+
import logging
|
|
26
|
+
import threading
|
|
27
|
+
from typing import TYPE_CHECKING, Any, Protocol
|
|
28
|
+
|
|
29
|
+
import httpx2 as httpx
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from acumatica.ratelimit import RateLimiter
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
# Refresh a little early, so a call that starts just inside the window cannot
|
|
37
|
+
# finish just outside it. Lands correctly against the measured hard 3600s TTL.
|
|
38
|
+
_REFRESH_MARGIN = timedelta(minutes=5)
|
|
39
|
+
|
|
40
|
+
# Only if Acumatica ever stops sending `expires_in`. Deliberately shorter than
|
|
41
|
+
# the hour it actually grants: re-fetching a token that was still good costs
|
|
42
|
+
# one request, and treating a dead one as live costs every call after it.
|
|
43
|
+
_ASSUMED_TTL = timedelta(minutes=30)
|
|
44
|
+
|
|
45
|
+
# A URL path, not a credential -- S105 matches on the word "token".
|
|
46
|
+
_TOKEN_PATH = "/identity/connect/token" # noqa: S105
|
|
47
|
+
|
|
48
|
+
# `api` buys the REST API, the screen-based SOAP API and OData.
|
|
49
|
+
# `offline_access` buys the refresh token, and with it the single reused
|
|
50
|
+
# session. `api:concurrent_access` is deliberately absent: it hands out
|
|
51
|
+
# multiple cookie-managed sessions that must each be signed out explicitly.
|
|
52
|
+
DEFAULT_SCOPE = "api offline_access"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AcumaticaAuthError(Exception):
|
|
56
|
+
"""Raised when the identity endpoint refuses to issue a token."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, message: str, error: str | None = None):
|
|
59
|
+
self.error = error
|
|
60
|
+
super().__init__(f"Acumatica auth error: {message}")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TokenStore(Protocol):
|
|
64
|
+
"""Somewhere a refresh token survives between processes.
|
|
65
|
+
|
|
66
|
+
The access token is deliberately not persisted. It lives an hour, and a
|
|
67
|
+
stale one costs a round trip to discover.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def load(self) -> str | None:
|
|
71
|
+
"""Return the stored refresh token, or None if there is none."""
|
|
72
|
+
...
|
|
73
|
+
|
|
74
|
+
def save(self, refresh_token: str) -> None:
|
|
75
|
+
"""Replace the stored refresh token."""
|
|
76
|
+
...
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class MemoryTokenStore:
|
|
80
|
+
"""A token store that lasts as long as the process.
|
|
81
|
+
|
|
82
|
+
The default, and the right one for a script or a test. A Lambda should pass
|
|
83
|
+
a store backed by Secrets Manager or Parameter Store so the chain survives
|
|
84
|
+
a cold start -- but see the warning on `OAuthSession` first.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(self, refresh_token: str | None = None):
|
|
88
|
+
self._refresh_token = refresh_token
|
|
89
|
+
|
|
90
|
+
def load(self) -> str | None:
|
|
91
|
+
return self._refresh_token
|
|
92
|
+
|
|
93
|
+
def save(self, refresh_token: str) -> None:
|
|
94
|
+
self._refresh_token = refresh_token
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class OAuthSession:
|
|
98
|
+
"""Holds a live access token, refreshing it as it ages out.
|
|
99
|
+
|
|
100
|
+
Warning:
|
|
101
|
+
A persisted refresh token is *mutable shared state*. Refresh tokens are
|
|
102
|
+
single-use and rotate, so if several workers cold-start and refresh from
|
|
103
|
+
the same stored value, one wins and the rest get `invalid_grant`. If a
|
|
104
|
+
loser then writes its spent token back, the chain is destroyed and only
|
|
105
|
+
a password grant recovers it.
|
|
106
|
+
|
|
107
|
+
This bites precisely in the webhook-burst case. Prefer a single
|
|
108
|
+
refresher -- one rate-limited queue consumer rather than a worker per
|
|
109
|
+
notification -- or a store that does conditional writes.
|
|
110
|
+
|
|
111
|
+
This class never clears a refresh token it failed to redeem, because a
|
|
112
|
+
failure is equally consistent with another worker having already
|
|
113
|
+
rotated it. It falls back to the password grant instead, which writes a
|
|
114
|
+
fresh one.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
base_url: str,
|
|
120
|
+
client_id: str,
|
|
121
|
+
client_secret: str,
|
|
122
|
+
username: str,
|
|
123
|
+
password: str,
|
|
124
|
+
*,
|
|
125
|
+
store: TokenStore | None = None,
|
|
126
|
+
scope: str = DEFAULT_SCOPE,
|
|
127
|
+
limiter: RateLimiter | None = None,
|
|
128
|
+
transport: httpx.BaseTransport | None = None,
|
|
129
|
+
timeout: float = 30.0,
|
|
130
|
+
):
|
|
131
|
+
"""Initialize the session.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
base_url (str): The instance root, e.g. `https://example.acumatica.com`.
|
|
135
|
+
client_id (str): The client ID from Connected Applications. It
|
|
136
|
+
carries the tenant after an `@`, as in `<guid>@MyTenant`, and
|
|
137
|
+
that is what scopes the session to a tenant -- there is no
|
|
138
|
+
separate tenant parameter.
|
|
139
|
+
client_secret (str): The shared secret for that client.
|
|
140
|
+
username (str): An Acumatica user with the Integration user type.
|
|
141
|
+
password (str): That user's password.
|
|
142
|
+
store (TokenStore, optional): Where the refresh token lives.
|
|
143
|
+
Defaults to a process-lifetime store.
|
|
144
|
+
scope (str, optional): The requested scope.
|
|
145
|
+
Defaults to `api offline_access`.
|
|
146
|
+
limiter (RateLimiter, optional): Token requests count against the
|
|
147
|
+
same tenant-wide budget as data requests, so the client passes
|
|
148
|
+
its limiter in. Defaults to None.
|
|
149
|
+
transport (httpx.BaseTransport, optional): A custom transport, e.g.
|
|
150
|
+
`httpx.MockTransport` for testing. Defaults to None.
|
|
151
|
+
timeout (float, optional): Request timeout in seconds.
|
|
152
|
+
Defaults to 30.0.
|
|
153
|
+
|
|
154
|
+
Raises:
|
|
155
|
+
ValueError: If any credential is missing.
|
|
156
|
+
"""
|
|
157
|
+
if not all([base_url, client_id, client_secret, username, password]):
|
|
158
|
+
raise ValueError(
|
|
159
|
+
"base_url, client_id, client_secret, username and password "
|
|
160
|
+
"are all required"
|
|
161
|
+
)
|
|
162
|
+
self._client_id = client_id
|
|
163
|
+
self._client_secret = client_secret
|
|
164
|
+
self._username = username
|
|
165
|
+
self._password = password
|
|
166
|
+
self._scope = scope
|
|
167
|
+
self._store: TokenStore = store if store is not None else MemoryTokenStore()
|
|
168
|
+
self._limiter = limiter
|
|
169
|
+
self._access_token: str | None = None
|
|
170
|
+
self._expires_at = datetime.min.replace(tzinfo=UTC)
|
|
171
|
+
# The refresh path is the one place in this package where concurrency
|
|
172
|
+
# is destructive rather than merely wasteful: a refresh token is
|
|
173
|
+
# single-use, so two threads redeeming the same one leaves a loser
|
|
174
|
+
# whose password-grant fallback overwrites the winner's rotated token.
|
|
175
|
+
# The chain then thrashes, with every worker invalidating the last.
|
|
176
|
+
# Between processes this needs a single refresher; within one, a lock.
|
|
177
|
+
self._lock = threading.Lock()
|
|
178
|
+
self._client = httpx.Client(
|
|
179
|
+
base_url=base_url.rstrip("/"),
|
|
180
|
+
timeout=timeout,
|
|
181
|
+
transport=transport,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def token(self) -> str:
|
|
185
|
+
"""Return an access token that has not expired.
|
|
186
|
+
|
|
187
|
+
Tries the stored refresh token first and falls back to the password
|
|
188
|
+
grant, which also covers the case nobody expects: by default the whole
|
|
189
|
+
refresh chain expires 30 days after the *initial* authentication, no
|
|
190
|
+
matter how often it is redeemed, unless Sliding Expiration is turned on
|
|
191
|
+
for the application on Connected Applications (SM303010).
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
str: A bearer token.
|
|
195
|
+
|
|
196
|
+
Raises:
|
|
197
|
+
AcumaticaAuthError: If neither grant succeeds.
|
|
198
|
+
"""
|
|
199
|
+
if self._access_token and datetime.now(UTC) < self._expires_at:
|
|
200
|
+
return self._access_token
|
|
201
|
+
|
|
202
|
+
with self._lock:
|
|
203
|
+
# Re-checked inside the lock: whoever held it was most likely
|
|
204
|
+
# refreshing, and the winner's token serves everyone queued behind
|
|
205
|
+
# it. Without this each waiter redeems in turn, which is the exact
|
|
206
|
+
# single-use replay the lock is here to prevent.
|
|
207
|
+
if self._access_token and datetime.now(UTC) < self._expires_at:
|
|
208
|
+
return self._access_token
|
|
209
|
+
|
|
210
|
+
if refresh_token := self._store.load():
|
|
211
|
+
try:
|
|
212
|
+
return self._grant(
|
|
213
|
+
{
|
|
214
|
+
"grant_type": "refresh_token",
|
|
215
|
+
"refresh_token": refresh_token,
|
|
216
|
+
}
|
|
217
|
+
)
|
|
218
|
+
except AcumaticaAuthError as exc:
|
|
219
|
+
# Expected, and not an error: the chain hit its 30-day
|
|
220
|
+
# absolute lifetime, or another process rotated it out
|
|
221
|
+
# from under us.
|
|
222
|
+
logger.info(
|
|
223
|
+
"Acumatica refresh token rejected; falling back to the "
|
|
224
|
+
"password grant",
|
|
225
|
+
extra={"error": exc.error},
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
return self._grant(
|
|
229
|
+
{
|
|
230
|
+
"grant_type": "password",
|
|
231
|
+
"username": self._username,
|
|
232
|
+
"password": self._password,
|
|
233
|
+
"scope": self._scope,
|
|
234
|
+
}
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
def invalidate(self) -> None:
|
|
238
|
+
"""Forget the cached access token.
|
|
239
|
+
|
|
240
|
+
Called when a request comes back 401 despite the token looking live --
|
|
241
|
+
the clocks disagreed, or the session was closed server-side.
|
|
242
|
+
"""
|
|
243
|
+
self._access_token = None
|
|
244
|
+
self._expires_at = datetime.min.replace(tzinfo=UTC)
|
|
245
|
+
|
|
246
|
+
def _grant(self, data: dict[str, str]) -> str:
|
|
247
|
+
"""Redeem a grant and cache what comes back.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
data (dict[str, str]): The grant-specific body fields.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
str: The new access token.
|
|
254
|
+
|
|
255
|
+
Raises:
|
|
256
|
+
AcumaticaAuthError: If the endpoint refuses the grant.
|
|
257
|
+
"""
|
|
258
|
+
if self._limiter is not None:
|
|
259
|
+
self._limiter.acquire()
|
|
260
|
+
response = self._client.post(
|
|
261
|
+
_TOKEN_PATH,
|
|
262
|
+
data={
|
|
263
|
+
**data,
|
|
264
|
+
"client_id": self._client_id,
|
|
265
|
+
"client_secret": self._client_secret,
|
|
266
|
+
},
|
|
267
|
+
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
268
|
+
)
|
|
269
|
+
body = _body(response)
|
|
270
|
+
if not response.is_success:
|
|
271
|
+
raise AcumaticaAuthError(
|
|
272
|
+
body.get("error_description") or body.get("error") or response.text,
|
|
273
|
+
error=body.get("error"),
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
access_token = body.get("access_token")
|
|
277
|
+
if not access_token:
|
|
278
|
+
raise AcumaticaAuthError("the response carried no access_token")
|
|
279
|
+
|
|
280
|
+
expires_in = body.get("expires_in")
|
|
281
|
+
ttl = timedelta(seconds=int(expires_in)) if expires_in else _ASSUMED_TTL
|
|
282
|
+
# Stored already reduced by the margin, so the comparison in `token`
|
|
283
|
+
# stays a plain one and there is one place to be wrong about it.
|
|
284
|
+
self._expires_at = datetime.now(UTC) + ttl - _REFRESH_MARGIN
|
|
285
|
+
self._access_token = access_token
|
|
286
|
+
|
|
287
|
+
if refresh_token := body.get("refresh_token"):
|
|
288
|
+
self._store.save(refresh_token)
|
|
289
|
+
|
|
290
|
+
logger.info(
|
|
291
|
+
"Acumatica access token issued",
|
|
292
|
+
extra={
|
|
293
|
+
"grant_type": data["grant_type"],
|
|
294
|
+
"ttl_minutes": round(ttl.total_seconds() / 60, 1),
|
|
295
|
+
"rotated_refresh_token": bool(body.get("refresh_token")),
|
|
296
|
+
},
|
|
297
|
+
)
|
|
298
|
+
return access_token
|
|
299
|
+
|
|
300
|
+
def close(self) -> None:
|
|
301
|
+
"""Close the underlying HTTP connection."""
|
|
302
|
+
self._client.close()
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _body(response: httpx.Response) -> dict[str, Any]:
|
|
306
|
+
"""Parse a token response that may not be JSON.
|
|
307
|
+
|
|
308
|
+
Args:
|
|
309
|
+
response (httpx.Response): The response from the identity endpoint.
|
|
310
|
+
|
|
311
|
+
Returns:
|
|
312
|
+
dict[str, Any]: The parsed body, or an empty dict.
|
|
313
|
+
"""
|
|
314
|
+
try:
|
|
315
|
+
body = response.json()
|
|
316
|
+
except ValueError:
|
|
317
|
+
return {}
|
|
318
|
+
return body if isinstance(body, dict) else {}
|
acumatica/client.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""The Acumatica contract-based REST client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from json import JSONDecodeError
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx2 as httpx
|
|
9
|
+
from tenacity import (
|
|
10
|
+
retry,
|
|
11
|
+
retry_if_exception_type,
|
|
12
|
+
stop_after_attempt,
|
|
13
|
+
wait_exponential,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from acumatica.auth import OAuthSession, TokenStore
|
|
17
|
+
from acumatica.endpoints.base import DEFAULT_PAGE_SIZE, Entity
|
|
18
|
+
from acumatica.errors import AcumaticaError, AcumaticaRetryableError
|
|
19
|
+
from acumatica.ratelimit import DEFAULT_BURST, DEFAULT_REQUESTS_PER_MINUTE, RateLimiter
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"DEFAULT_ENDPOINT",
|
|
23
|
+
"DEFAULT_PAGE_SIZE",
|
|
24
|
+
"DEFAULT_VERSION",
|
|
25
|
+
"Acumatica",
|
|
26
|
+
"AcumaticaError",
|
|
27
|
+
"AcumaticaRetryableError",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
# The newest of each system endpoint deployed on the instance, confirmed
|
|
31
|
+
# against `GET /entity`. The version is part of the contract and not a
|
|
32
|
+
# formality: `Default/26.200.001` is contract version 5, which changes both the
|
|
33
|
+
# query syntax (`$expand=Operations($expand=Material)` rather than
|
|
34
|
+
# `Operations/Material`) and the data shape (a dropdown returns an ID and a
|
|
35
|
+
# description rather than a plain value). Pin it, and treat a bump as breaking.
|
|
36
|
+
DEFAULT_ENDPOINT = "Default"
|
|
37
|
+
DEFAULT_VERSION = "25.200.001"
|
|
38
|
+
|
|
39
|
+
# Retried rather than raised. The shape of a throttle response is *not* among
|
|
40
|
+
# the things measured on this instance -- exceeding 150/min needs a quiet
|
|
41
|
+
# window and permission -- so 429 is included on the strength of the HTTP spec
|
|
42
|
+
# rather than observation.
|
|
43
|
+
_RETRY_STATUSES = frozenset({429, 502, 503, 504})
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _error_message(response: httpx.Response) -> Any:
|
|
47
|
+
"""Pull a message off a failed response that may not be JSON.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
response (httpx.Response): The failed response.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
Any: The most specific message available, or the raw text.
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
body = response.json()
|
|
57
|
+
except JSONDecodeError, UnicodeDecodeError, ValueError:
|
|
58
|
+
return response.text
|
|
59
|
+
if isinstance(body, dict):
|
|
60
|
+
return (
|
|
61
|
+
body.get("exceptionMessage")
|
|
62
|
+
or body.get("message")
|
|
63
|
+
or body.get("error")
|
|
64
|
+
or body
|
|
65
|
+
)
|
|
66
|
+
return body
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Acumatica:
|
|
70
|
+
"""A client for one endpoint of one Acumatica instance.
|
|
71
|
+
|
|
72
|
+
An endpoint is a contract, not a namespace, so a client is bound to one.
|
|
73
|
+
Reading manufacturing data alongside the financial and inventory entities
|
|
74
|
+
means a second client against `MANUFACTURING`.
|
|
75
|
+
|
|
76
|
+
Read-only by design in this version. The ODS mirrors the ERP rather than
|
|
77
|
+
driving it, and `PUT` can create as well as update -- so write support is
|
|
78
|
+
left until something actually needs it rather than shipped as a loaded gun.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def __init__(
|
|
82
|
+
self,
|
|
83
|
+
base_url: str,
|
|
84
|
+
client_id: str,
|
|
85
|
+
client_secret: str,
|
|
86
|
+
username: str,
|
|
87
|
+
password: str,
|
|
88
|
+
*,
|
|
89
|
+
endpoint: str = DEFAULT_ENDPOINT,
|
|
90
|
+
version: str = DEFAULT_VERSION,
|
|
91
|
+
requests_per_minute: int = DEFAULT_REQUESTS_PER_MINUTE,
|
|
92
|
+
burst: int = DEFAULT_BURST,
|
|
93
|
+
token_store: TokenStore | None = None,
|
|
94
|
+
transport: httpx.BaseTransport | None = None,
|
|
95
|
+
timeout: float = 60.0,
|
|
96
|
+
limiter: RateLimiter | None = None,
|
|
97
|
+
session: OAuthSession | None = None,
|
|
98
|
+
):
|
|
99
|
+
"""Initialize the client.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
base_url (str): The instance root, e.g. `https://example.acumatica.com`.
|
|
103
|
+
client_id (str): The client ID from Connected Applications,
|
|
104
|
+
including the `@Tenant` suffix that scopes it.
|
|
105
|
+
client_secret (str): The shared secret for that client.
|
|
106
|
+
username (str): An Acumatica user with the Integration user type.
|
|
107
|
+
password (str): That user's password.
|
|
108
|
+
endpoint (str, optional): The endpoint name. Defaults to `Default`.
|
|
109
|
+
version (str, optional): The endpoint version.
|
|
110
|
+
Defaults to `25.200.001`.
|
|
111
|
+
requests_per_minute (int, optional): The sustained request budget.
|
|
112
|
+
Defaults to 100, against a measured tenant-wide cap of 150.
|
|
113
|
+
burst (int, optional): How many requests may go out back-to-back.
|
|
114
|
+
Defaults to 10.
|
|
115
|
+
token_store (TokenStore, optional): Where the refresh token lives
|
|
116
|
+
between processes. Defaults to a process-lifetime store.
|
|
117
|
+
transport (httpx.BaseTransport, optional): A custom transport, e.g.
|
|
118
|
+
`httpx.MockTransport` for testing. Shared with the identity
|
|
119
|
+
endpoint, so a mock must route both. Defaults to None.
|
|
120
|
+
timeout (float, optional): Request timeout in seconds.
|
|
121
|
+
Defaults to 60.0.
|
|
122
|
+
limiter (RateLimiter, optional): A limiter to share. **Pass one
|
|
123
|
+
whenever a process holds more than one client.** An endpoint
|
|
124
|
+
is a contract, so reading manufacturing alongside inventory
|
|
125
|
+
takes two clients — and two clients each owning a private
|
|
126
|
+
limiter pace to 200/min against a tenant-wide cap of 150.
|
|
127
|
+
Defaults to a private limiter.
|
|
128
|
+
session (OAuthSession, optional): A session to share. Both clients
|
|
129
|
+
address the same instance with the same credentials, so a
|
|
130
|
+
shared session is one token, one refresh chain and one of the
|
|
131
|
+
20 API user slots rather than two of each. Defaults to a
|
|
132
|
+
private session. When given, `token_store` is ignored, since
|
|
133
|
+
the session already owns its store.
|
|
134
|
+
|
|
135
|
+
Note:
|
|
136
|
+
`close()` shuts down whatever this client was given. Sharing a
|
|
137
|
+
session means the first client closed ends it for the others, so
|
|
138
|
+
close the borrowers first or let a single owner do it.
|
|
139
|
+
"""
|
|
140
|
+
self.endpoint = endpoint
|
|
141
|
+
self.version = version
|
|
142
|
+
self._limiter = limiter or RateLimiter(requests_per_minute, burst)
|
|
143
|
+
self._session = session or OAuthSession(
|
|
144
|
+
base_url,
|
|
145
|
+
client_id,
|
|
146
|
+
client_secret,
|
|
147
|
+
username,
|
|
148
|
+
password,
|
|
149
|
+
store=token_store,
|
|
150
|
+
limiter=self._limiter,
|
|
151
|
+
transport=transport,
|
|
152
|
+
timeout=timeout,
|
|
153
|
+
)
|
|
154
|
+
self._client = httpx.Client(
|
|
155
|
+
base_url=f"{base_url.rstrip('/')}/entity/{endpoint}/{version}/",
|
|
156
|
+
headers={"Accept": "application/json"},
|
|
157
|
+
timeout=timeout,
|
|
158
|
+
transport=transport,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def limiter(self) -> RateLimiter:
|
|
163
|
+
"""The limiter this client paces against.
|
|
164
|
+
|
|
165
|
+
Public so a sibling client for another endpoint can be handed the same
|
|
166
|
+
one. Two private limiters in one process spend twice the budget.
|
|
167
|
+
"""
|
|
168
|
+
return self._limiter
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def session(self) -> OAuthSession:
|
|
172
|
+
"""The OAuth session this client authenticates with.
|
|
173
|
+
|
|
174
|
+
Public so a sibling client for another endpoint can share it. An
|
|
175
|
+
endpoint is a contract rather than a credential boundary, so both
|
|
176
|
+
clients want the same token and the same API user slot.
|
|
177
|
+
"""
|
|
178
|
+
return self._session
|
|
179
|
+
|
|
180
|
+
def entity(self, name: str) -> Entity:
|
|
181
|
+
"""Return a handle on one entity of this endpoint.
|
|
182
|
+
|
|
183
|
+
Deliberately not a set of named attributes, unlike the other source
|
|
184
|
+
clients in the house. Those wrap a fixed vendor API; Acumatica's entity
|
|
185
|
+
set is a property of the endpoint and can be extended per instance, so
|
|
186
|
+
a list baked into this package would be wrong somewhere. The names
|
|
187
|
+
proven readable on this instance are in `acumatica.entities`.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
name (str): The entity name, e.g. `StockItem`.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
Entity: A read-only handle on that entity.
|
|
194
|
+
"""
|
|
195
|
+
return Entity(self, name)
|
|
196
|
+
|
|
197
|
+
@retry(
|
|
198
|
+
reraise=True,
|
|
199
|
+
stop=stop_after_attempt(3),
|
|
200
|
+
wait=wait_exponential(multiplier=1, min=2, max=10),
|
|
201
|
+
retry=retry_if_exception_type(
|
|
202
|
+
(httpx.TimeoutException, AcumaticaRetryableError)
|
|
203
|
+
),
|
|
204
|
+
)
|
|
205
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
206
|
+
"""Send one authenticated, rate-limited request.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
method (str): The HTTP method.
|
|
210
|
+
path (str): The path below the endpoint root.
|
|
211
|
+
**kwargs: Forwarded to httpx.
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
Any: The parsed JSON body, or an empty dict for an empty response.
|
|
215
|
+
|
|
216
|
+
Raises:
|
|
217
|
+
AcumaticaError: On any non-success response that survives a retry.
|
|
218
|
+
"""
|
|
219
|
+
response = self._send(method, path, **kwargs)
|
|
220
|
+
|
|
221
|
+
if response.status_code == 401:
|
|
222
|
+
# The token looked live and was not: clocks disagreed, or the
|
|
223
|
+
# session was closed server-side. One forced refresh, then give up
|
|
224
|
+
# -- a second 401 is a credentials problem, and retrying it burns
|
|
225
|
+
# budget and risks the API user limit.
|
|
226
|
+
self._session.invalidate()
|
|
227
|
+
response = self._send(method, path, **kwargs)
|
|
228
|
+
|
|
229
|
+
if response.status_code in _RETRY_STATUSES:
|
|
230
|
+
raise AcumaticaRetryableError(
|
|
231
|
+
response.status_code, _error_message(response)
|
|
232
|
+
)
|
|
233
|
+
if not response.is_success:
|
|
234
|
+
raise AcumaticaError(response.status_code, _error_message(response))
|
|
235
|
+
if not response.content:
|
|
236
|
+
return {}
|
|
237
|
+
return response.json()
|
|
238
|
+
|
|
239
|
+
def _send(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
|
|
240
|
+
"""Spend a token from the budget and send, with a fresh bearer header.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
method (str): The HTTP method.
|
|
244
|
+
path (str): The path below the endpoint root.
|
|
245
|
+
**kwargs: Forwarded to httpx.
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
httpx.Response: The raw response, success or not.
|
|
249
|
+
"""
|
|
250
|
+
self._limiter.acquire()
|
|
251
|
+
headers = {
|
|
252
|
+
"Authorization": f"Bearer {self._session.token()}",
|
|
253
|
+
**kwargs.pop("headers", {}),
|
|
254
|
+
}
|
|
255
|
+
return self._client.request(method, path, headers=headers, **kwargs)
|
|
256
|
+
|
|
257
|
+
def get(self, path: str, **kwargs: Any) -> Any:
|
|
258
|
+
"""Get a resource from the REST API.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
path (str): The path below the endpoint root.
|
|
262
|
+
**kwargs: Additional arguments forwarded to the request.
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
Any: The parsed response.
|
|
266
|
+
"""
|
|
267
|
+
return self._request("GET", path, **kwargs)
|
|
268
|
+
|
|
269
|
+
def __enter__(self) -> Acumatica:
|
|
270
|
+
return self
|
|
271
|
+
|
|
272
|
+
def __exit__(self, *_: Any) -> None:
|
|
273
|
+
self.close()
|
|
274
|
+
|
|
275
|
+
def close(self) -> None:
|
|
276
|
+
"""Close both underlying HTTP connections.
|
|
277
|
+
|
|
278
|
+
No sign-out is sent. With the `api` and `offline_access` scopes
|
|
279
|
+
Acumatica reuses one session across the refresh chain and closes it
|
|
280
|
+
when the chain ends, so signing out here would discard a session the
|
|
281
|
+
next cold start wants to resume.
|
|
282
|
+
"""
|
|
283
|
+
self._client.close()
|
|
284
|
+
self._session.close()
|
|
File without changes
|