ebarimt-pos-sdk
A modern, async-first Python SDK for the Ebarimt POS API 3.0 — Mongolia's electronic receipting (e-баримт) platform. It wraps both the public OAuth2 API and the local REST API exposed by POS devices behind a single, typed, ergonomic interface.
📖 Full documentation: https://ebarimt-pos-sdk.readthedocs.io/mn/latest/ 📘 Ebarimt POS API 3.0 reference: https://developer.itc.gov.mn/docs/ebarimt-api/inbishdm2zj3x-pos-api-3-0-sistemijn-api-holbolt-zaavruud 🇲🇳 Mongolian version of this README: README_MN.md
Features
- Async-first — every operation exposes both a synchronous and an
asyncvariant (method()/amethod()), built onhttpx. - Strictly typed — Pydantic v2 models with camelCase ↔ snake_case aliasing; type-checked with
ty. - Two focused clients —
EbarimtApiClientfor the public OAuth2 API,EbarimtRestClientfor the local POS REST API. - Managed OAuth2 — built-in password-grant flow with automatic token refresh and proactive expiry handling.
- Resilient transport — configurable retry with jittered exponential backoff on 429/5xx and network errors for
idempotent methods (
GET/HEAD/OPTIONS/PUT/DELETE), per-request timeouts, and TLS verification.POSTis never retried unless you opt in, so a lost response can't become a duplicate receipt. - Structured errors — a clear exception hierarchy distinguishing transport, HTTP, decode, validation, and business failures. Sensitive headers and tokens are automatically redacted from error output.
- Environment presets — one-line switch between
STAGINGandPRODUCTIONendpoints viacreate_api_settings.
Installation
pip install ebarimt-pos-sdk
Or with uv:
uv add ebarimt-pos-sdk
Requires Python 3.10 or newer.
Quick Start
Local REST client — issue a receipt
from ebarimt_pos_sdk import EbarimtRestClient, RestClientSettings
settings = RestClientSettings(base_url="http://localhost:1234")
with EbarimtRestClient(settings) as client:
receipt = client.receipt.create(
{
"branch_no": "001",
"total_amount": 10000,
"merchant_tin": "1234567890",
"pos_no": "POS001",
"type": "B2C_RECEIPT",
"bill_id_suffix": "A",
"receipts": [
{
"total_amount": 10000,
"tax_type": "VAT_ABLE",
"merchant_tin": "1234567890",
"items": [
{
"name": "Product",
"measure_unit": "ш",
"qty": 1,
"unit_price": 10000,
"total_amount": 10000,
}
],
}
],
}
)
print(receipt.id, receipt.qr_data)
Async variant: swap with for async with and call await client.receipt.acreate(...).
import asyncio
from ebarimt_pos_sdk import EbarimtRestClient, RestClientSettings
async def main() -> None:
async with EbarimtRestClient(RestClientSettings(base_url="http://localhost:1234")) as client:
receipt = await client.receipt.acreate(payload)
print(receipt.id)
asyncio.run(main())
Public API client — look up a TIN
Use the factory to target a specific environment without hard-coding URLs:
from ebarimt_pos_sdk import (
EbarimtApiClient,
Environment,
create_api_settings,
)
settings = create_api_settings(
Environment.PRODUCTION, # or Environment.STAGING
client_id="your_client_id",
username="your_username",
password="your_password",
)
with EbarimtApiClient(settings=settings) as client:
info = client.tin_info.read("1234567890")
print(info.data)
Routing through a proxy
The public API may only be reachable from a specific region (e.g. Mongolia). Route the API client through an
HTTP/SOCKS proxy with the proxy argument:
with EbarimtApiClient(settings, proxy="http://user:pass@mn-proxy:8080") as client:
info = client.tin_info.read("1234567890")
proxy accepts a URL string or an httpx.Proxy; SOCKS proxies need the httpx[socks] extra. It cannot be
combined with an injected sync_client/async_client — set the proxy on that client instead. The local
EbarimtRestClient has no proxy argument (it talks to a POS device on your own network).
Clients at a glance
| Client | Authentication | Available resources |
|---|---|---|
EbarimtRestClient |
None (local network) | receipt, info, send_data, bank_accounts |
EbarimtApiClient |
OAuth2 password grant | district_code, tin_info, merchant_info, product_tax_code |
Both clients support synchronous and asynchronous context managers, share a common settings base (timeouts, TLS, headers, retry policy), and reuse the same error hierarchy.
Error handling
The SDK surfaces failures through a focused exception hierarchy, so you can react at the level of abstraction that matters to your code:
PosApiError
├── PosApiTransportError # network / timeout / DNS / TLS
├── PosApiDecodeError # response body was not valid JSON
├── PosApiHttpError # non-2xx response from server
├── PosApiBusinessError # 2xx, but domain-level failure in payload
└── PosApiValidationError # Pydantic validation of request or response
from ebarimt_pos_sdk import (
PosApiBusinessError,
PosApiHttpError,
PosApiTransportError,
PosApiValidationError,
)
try:
receipt = client.receipt.create(payload)
except PosApiValidationError as e:
# Bad shape — fix the request before resending
for err in e.errors:
print(err["loc"], err["msg"])
except PosApiBusinessError as e:
# Server accepted the request but rejected it on business grounds
print(e.status, e.code, e.message)
except PosApiHttpError as e:
# 4xx / 5xx — includes safe, redacted request/response context
print(e)
except PosApiTransportError as e:
# Network layer. e.cause is the underlying httpx exception.
if not e.request_sent:
# Never left the client (connection refused, DNS, connect timeout, proxy
# refused, OAuth token fetch failed): PosAPI cannot hold this receipt,
# so resending is safe.
...
else:
# The request may have reached PosAPI and the answer was lost (read
# timeout, dropped connection, ...). For a POST such as receipt.create
# the receipt may already exist: reconcile before resending, or you
# risk issuing a duplicate е-баримт.
raise
request_sent is False only for failures that prove the request was never written
(httpx.ConnectError, httpx.ConnectTimeout, httpx.ProxyError, or a failed token fetch before
the request). Anything else, including exceptions the SDK does not recognise, reports True.
When idempotent requests are retried, the error describes the final attempt.
Authorization headers and token-bearing query parameters are redacted automatically in every error's string
representation.
Configuration
All settings are immutable dataclasses — construct once and pass to the client. Timeouts, TLS verification, custom
headers, and retry behaviour are shared across both clients via BaseSettings.
from ebarimt_pos_sdk import RestClientSettings
from ebarimt_pos_sdk.settings import RetrySettings
settings = RestClientSettings(
base_url="http://localhost:1234",
timeout_s=5.0,
verify_tls=True,
headers={"X-Request-Source": "pos-42"},
retry=RetrySettings(
max_retries=3,
backoff_base_seconds=1.0,
max_backoff_seconds=30.0,
jitter=True, # full jitter: sleep ~ U(0, backoff)
respect_retry_after=True, # server's Retry-After wins (capped)
retryable_statuses=frozenset({429, 500, 502, 503, 504}),
retry_methods=RetrySettings.DEFAULT_RETRY_METHODS, # GET/HEAD/OPTIONS/PUT/DELETE
retry_unsent=False, # True: re-send POST/PATCH only if it never left the client
),
)
The default retry policy — 3 attempts with jittered exponential backoff on 429/5xx and network errors — is suitable
for most deployments. Full jitter (a uniform draw in [0, backoff]) stops a fleet of POS devices that fail together
from retrying in lockstep; a Retry-After header (delta-seconds or HTTP-date) replaces the computed backoff, capped at
max_backoff_seconds. Set jitter=False for deterministic timing in tests.
Retries only apply to idempotent methods. receipt.create is a POST: if the local PosAPI persists the receipt
but the response is lost to a timeout, a retry would issue a second е-баримт. The SDK therefore sends POST (and
PATCH) exactly once regardless of max_retries. If your deployment can tolerate or detect duplicates, opt in:
RetrySettings(retry_methods=RetrySettings.DEFAULT_RETRY_METHODS | {"POST"})
A safer middle ground is retry_unsent=True. It re-sends POST/PATCH only after a failure that proves the
request never left the client: connection refused, DNS failure, connect timeout, or a proxy that refused the tunnel
(the cases where PosApiTransportError.request_sent is False). PosAPI cannot hold a receipt it never received, so
this cannot create a duplicate. Anything else still ends after the first attempt, including any response (even
503) and any failure after the request may have been sent (read timeout, dropped connection):
RetrySettings(retry_unsent=True) # e.g. ride out a POS that is briefly unreachable
Logging
The SDK logs through the standard library under the ebarimt_pos_sdk namespace and follows library-logging
hygiene: a NullHandler is attached, so nothing is emitted until your application configures logging. The SDK
never adds handlers or sets levels itself.
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("ebarimt_pos_sdk").setLevel(logging.DEBUG)
What you get:
DEBUG— one line per request and response:→ POST /rest/receipt [a1b2c3d4]/← 200 in 42ms [a1b2c3d4].WARNING— one line per retried attempt:retry 1/3 after 503, sleeping 1.00s [a1b2c3d4].- Failures are not logged — they raise a typed
PosApiError. The samerequest_idis available aserror.request_id, so an exception in production correlates with the log lines.
Each record also carries structured fields (request_id, http_method, http_status, duration_ms, attempt)
via extra=, ready for JSON log pipelines.
Safety: records are metadata only — method, status, timing, ids. Headers and request/response bodies are never logged. URLs have sensitive query parameters (tokens, secrets) masked. Path segments are left intact; the only identifiers the SDK puts in a path are TINs, which are public.
To also see httpx's own output, configure its loggers directly — httpx at INFO emits an HTTP Request: line
(note: the raw URL, unredacted), and httpcore at DEBUG emits connection/wire detail:
import logging.config
logging.config.dictConfig(
{
"version": 1,
"handlers": {"default": {"class": "logging.StreamHandler"}},
"loggers": {
"ebarimt_pos_sdk": {"handlers": ["default"], "level": "DEBUG"},
"httpx": {"handlers": ["default"], "level": "INFO"},
"httpcore": {"handlers": ["default"], "level": "WARNING"},
},
}
)
Validation philosophy
The SDK validates structure, not policy:
- ✅ Field shapes, regex for stable identifiers (TIN, branch codes), enums, and basic numeric constraints (
>= 0). - ❌ Business rules, cross-field dependencies, reference-table lookups, or any government policy that changes out of band.
This boundary is intentional. The server owns business rules; the SDK owns shape correctness. That keeps the SDK stable when rules change.
Development
# Install all dependencies, including dev extras
uv sync --dev
# Run the unit test suite
uv run pytest -m "not integration"
# Run with coverage
uv run pytest -m "not integration" --cov
# Lint and format
uv run ruff check
uv run ruff format
# Type check
uv run ty check
Integration tests (marked @pytest.mark.integration) require a live PosAPI server and credentials; they are excluded
from CI by default.
See CONTRIBUTING.md for contribution guidelines and CHANGELOG.md for release notes.
License
Released under the MIT License.
Metadata
Release files for ebarimt-pos-sdk 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ebarimt_pos_sdk-0.6.0.tar.gz | 29.6 kB | With provenance | Details for ebarimt_pos_sdk-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ebarimt_pos_sdk-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for ebarimt_pos_sdk-0.6.0-py3-none-any.whl |
Total release size: 78.0 kB
Release files / ebarimt_pos_sdk-0.6.0.tar.gz
| Download URL | ebarimt_pos_sdk-0.6.0.tar.gz |
|---|---|
| Size | 29.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
42c5dd05267c5e8db36da5fa3cf3031dabd4903b25785ac65211602ea0aa9ed5
|
|
BLAKE2b-256 checksum How to use checksums |
eba0fbac7e129d3f466fe490193f04d9a944e750280c185c5b365dec5844ceb1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logRelease files / ebarimt_pos_sdk-0.6.0-py3-none-any.whl
| Download URL | ebarimt_pos_sdk-0.6.0-py3-none-any.whl |
|---|---|
| Size | 48.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
25e471aa6be76318f74afe12b8bce28faf9232c8491f0841ed19fb091cbe9a90
|
|
BLAKE2b-256 checksum How to use checksums |
f584adb5d0134c430ab55b63a84de42ff547f3a7854df75e0e3ffc6e2154149e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logSecurity for ebarimt-pos-sdk 0.6.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ebarimt_pos_sdk-0.6.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.