bachs is the official Bachs library for Python servers. It sends authenticated requests, checks and types the responses, retries reads safely, and verifies webhook signatures. It has a sync client, Bachs, and an async client, AsyncBachs, with the same methods.
It runs on your server only. Keep your secret API key out of browser and mobile code.
Install
You need Python 3.10 or later.httpx and ships type hints for mypy and Pyright.
Create a client
Create one client and reuse it. Pass your secret key.sk_sandbox_ sends requests to https://sandbox-api.bachs.io, and a key that starts with sk_live_ sends them to https://api.bachs.io. bachs.environment tells you which one is in use. See API keys and authentication.
You can pass environment as well. If it contradicts the key, for example "production" with a sandbox key, the constructor raises BachsConfigError instead of sending the key to the wrong host. A key with another prefix needs environment set.
Creating a client sends no request, so an invalid key shows up on your first call.
To release connections when you are done, use the client as a context manager (
with Bachs(...) as bachs: or async with AsyncBachs(...) as bachs:), or call bachs.close() or await bachs.aclose().
Send requests
Each resource on the client maps to a group of API endpoints. Request fields are keyword arguments, and methods follow one pattern:- Create:
create(*, fields..., idempotency_key=None, timeout=None) - Retrieve:
get(id, *, timeout=None, max_retries=None) - List:
list(*, filters..., timeout=None, max_retries=None)for one page,list_all(*, filters...)for every item
AsyncBachs, every method is a coroutine: await bachs.products.create(...).
Fields have the same names as in the API, in snake_case, so the API reference describes them exactly. Money amounts are decimal strings, such as "12.00", never numbers. Nested values, such as a product’s price or an item in product_cart, are dictionaries.
Leaving an optional field out sends nothing for it. Passing None sends null. The API treats the two differently, and so does the SDK. A field the method does not know is a TypeError.
Responses
Responses are typed objects. Read fields as attributes:product.id, checkout.checkout_url, page.items[0].price.amount. Your editor completes them, and mypy or Pyright reports a misspelled field.
A field the API left out reads as None. Fields the API adds later, which this SDK version does not declare yet, are still readable. .to_dict() returns the JSON exactly as received, for storing or logging a response.
Resources
subscriptions.cancel(id, cancel_at_period_end=True) cancels at the end of the paid period; cancel_at_period_end=False cancels now. See Manage subscriptions.
Not in the SDK yet
Use the API directly for these. You can call it alongside the SDK with the same key.- Connect: connected accounts, onboarding, the
X-Account-Idheader and split payments - Customers, refunds, disputes and conversions
- Updating, archiving or unarchiving products, and changing a subscription’s seats or plan
- Virtual accounts, uploads, product groups and account settings
TypeError, so an unsupported field cannot be sent by accident.
Lists and pagination
list_all walks every page for you. It is an iterator (an async iterator with AsyncBachs) that fetches each page only when you reach it, so you can stop early without fetching the rest.
list, except the paging ones: cursor for products, offset for the rest. Pass limit to change the page size it requests.
list returns one page, in the same shape as the API response, when you want to page yourself. Products page by cursor, so pass pagination.next_cursor as cursor to get the next page. Payments, subscriptions, payouts and payout destinations page by limit and offset. Payout destinations are in destinations; the others are in items.
Request options
Every method takes these as keyword arguments alongside its fields.
To cancel an
AsyncBachs call, cancel its task, for example with asyncio.timeout() or when your framework drops a disconnected request. The cancellation exception reaches your code as usual. Cancelling stops waiting; it cannot undo a write Bachs already received.
Retries and uncertain writes
Reads are retried up tomax_retries times after a network failure or an HTTP 429, 500, 502, 503 or 504. The SDK waits about half a second, then a second, and follows any Retry-After header. It stops when the next wait would pass timeout.
Writes are sent once, even with an idempotency key. A write can reach Bachs and still fail on the way back, for example when the connection drops or the API returns a 5xx. In those cases the error has outcome_unknown set to True: the payment, payout or product may exist.
When a write’s outcome is unknown, do not send it again with a new key. Look it up first, for example in your payout history or by retrieving the checkout session. If it does not exist, repeat the write with the same idempotency key and the same request.
AsyncBachs stops exactly at timeout. The sync client can run past it in one case: when the server sends part of a response and then stops, the last network read waits for its own full timeout, so a call can take up to about twice timeout. If you need a hard limit, use AsyncBachs or set timeout to half of your limit.Errors
Every SDK error extendsBachsError. An API error carries two different codes, so they have two different names:
status_codeis the HTTP status code, a number such as404. See HTTP status codes.error_codeis the Bachs error code from the response body, a string such as"NOT_FOUND". Branch on it; it is stable. See the Error Reference.
field_errors is the errors array from the body, listing problems with individual fields. response_status_code on a network error is the HTTP status code when the response headers arrived before the failure. Include request_id when you contact support.
Error bodies and customer portal URLs can contain personal data or credentials. Do not log them in full.
Logging
The SDK logs through the standardlogging module under the name bachs, with no handler of its own, so your application controls it like any other library logger. Nothing is printed unless you configure logging.
The API key, request and response bodies, customer portal URLs and webhook secrets are never logged at any level.
Verify webhooks
webhooks.construct_event checks the signature on a delivery and returns the event. Pass the raw request body, before any JSON parsing, the request headers, and your endpoint’s signing secret. The signing secret is not your API key.
X-Bachs-Signature-V2, accepts any matching signature while you rotate a secret, and rejects deliveries more than 300 seconds old or ahead. Change the window with tolerance=, in seconds. You can call it without a client, or as bachs.webhooks.construct_event. The event is a typed object: event.id, event.type and event.data.
It does not deduplicate events or run your handlers. Your app stores processed event IDs and returns a 5xx when handling fails, so Bachs retries. See Webhooks.
Types
Response types are classes inbachs.types, and the shapes of nested request values are TypedDicts there:
Source code
The SDK is open source under the MIT license.- GitHub repository: source, issues and the full README
- PyPI package
- Changelog

