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: English ·
Монгол 📘 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
async variant (method() / amethod()), built
on httpx.
- Strictly typed — Pydantic v2 models with camelCase ↔ snake_case aliasing; type-checked with
ty.
- Two focused clients —
EbarimtApiClient for the public eBarimt API (no credentials needed),
EbarimtRestClient for the local POS REST API.
- 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. POST is 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
STAGING and PRODUCTION endpoints via create_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
)
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).
Registering merchants under your POS
An operator can add merchants to its POS without the operator portal. This is the only call that needs credentials:
an OAuth2 password-grant login and the X-API-KEY issued by eBarimt.
from ebarimt_pos_sdk import CreateMerchantRegistrationRequest
settings = create_api_settings(
Environment.STAGING,
client_id="your_client_id",
username="your_username",
password="your_password",
api_key="your_api_key",
)
with EbarimtApiClient(settings) as client:
ack = client.merchant_registration.create(
CreateMerchantRegistrationRequest(pos_no="10005299", merchant_tins=["77001059076"])
)
The call only submits a request; eBarimt approves it later. Poll EbarimtRestClient.info.read() until the TIN
appears among the POS's merchants. Missing credentials raise PosApiConfigurationError before anything is sent; a
refusal raises PosApiBusinessError with eBarimt's message.
Clients at a glance
| Client |
Authentication |
Available resources |
EbarimtRestClient |
None (local network) |
receipt, info, send_data, bank_accounts |
EbarimtApiClient |
None (public API)¹ |
district_code, tin_info, merchant_info, product_tax_code, buna, merchant_registration |
¹ Except merchant_registration, which needs an OAuth2 password-grant login and an API key.
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
└── PosApiConfigurationError # settings a call needs are missing; nothing sent
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, and retry
behaviour are shared across both clients via BaseSettings. Default headers are passed to the client constructor:
EbarimtRestClient(settings, headers={"X-Request-Source": "pos-42"}).
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,
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 same request_id is available as
error.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.