alfabank-sdk
Асинхронный Python SDK для Alfa API Альфа-Банка (интеграция host-to-host): выписки по счетам, сводка оборотов, информация об организации и её счетах.
- Python >= 3.10, полностью async (httpx), строгая типизация (pydantic v2,
py.typed) - Деньги —
Decimal, никаких float - Ретраи с учётом идемпотентности, опциональный rate limiter
- Две схемы аутентификации банка:
ApiKeyиBearer+ шовtoken_providerпод OAuth
⚠️ Disclaimer
Этот проект — НЕОФИЦИАЛЬНЫЙ SDK.
Он создан и поддерживается сообществом. Этот SDK не является официальным, не имеет отношения к АО «Альфа-Банк» (https://alfabank.ru), не одобрен и не спонсирован им. Все упомянутые торговые марки и названия принадлежат их законным владельцам.
Используете на свой страх и риск. Авторы и контрибьюторы не несут ответственности за любые последствия использования этой библиотеки.
This project is an UNOFFICIAL SDK.
It is community-maintained and is NOT affiliated with, endorsed by, sponsored by, or in any way officially connected with Alfa-Bank (АО «Альфа-Банк», https://alfabank.ru). All trademarks and product names mentioned belong to their respective owners.
Use at your own risk. The authors and contributors are not liable for any consequences arising from the use of this library.
Установка
pip install alfabank-sdk
Быстрый старт
import asyncio
from datetime import date
from alfabank import AlfaBankClient
async def main() -> None:
async with AlfaBankClient(api_key="ВАШ_КЛЮЧ") as client:
# Профиль организации и счета с балансами
info = await client.customer.info()
for account in info.accounts:
print(account.number, account.amount_balance)
# Выписка за дату (автопагинация)
async for tx in client.statements.iter_transactions(
"40702810102300000001", date(2026, 7, 1)
):
print(tx.direction, tx.amount.amount if tx.amount else None, tx.payment_purpose)
# Сводка оборотов
summary = await client.statements.summary("40702810102300000001", date(2026, 7, 1))
print(summary.closing_balance)
asyncio.run(main())
Аутентификация
Ровно один из трёх способов:
AlfaBankClient(api_key="...") # Authorization: ApiKey <key>
AlfaBankClient(access_token="...") # Authorization: Bearer <token>
AlfaBankClient(token_provider=provider) # (a)sync callable -> значение заголовка
OAuth-хелпер (experimental — контракт /oidc/token не проверен на живой песочнице):
from alfabank.oauth import OAuthTokenProvider
provider = OAuthTokenProvider(
client_id="...", client_secret="...", refresh_token="...",
)
client = AlfaBankClient(token_provider=provider)
Песочница и настройка окружения
from alfabank import SANDBOX_BASE_URL, AlfaBankClient
client = AlfaBankClient(api_key="...", base_url=SANDBOX_BASE_URL)
base_url и api_prefix настраиваются: шлюзовые пути могут отличаться
в зависимости от договора с банком. mTLS — через параметры cert/verify
(PEM) или инъекцию своего httpx.AsyncClient в http_client=.
Обработка ошибок
from alfabank import AlfaBankAPIError, AlfaBankRateLimitError
try:
page = await client.statements.transactions("40702810102300000001", "2026-07-01")
except AlfaBankRateLimitError as exc:
print("Лимит запросов, повторить через:", exc.retry_after)
except AlfaBankAPIError as exc:
print(exc.status_code, exc.error_code, exc.request_id, exc.response_body)
Эндпоинты
| Метод SDK | HTTP |
|---|---|
client.statements.transactions() |
GET {prefix}/statement/transactions |
client.statements.iter_transactions() |
автопагинация по _links rel=next |
client.statements.summary() |
GET {prefix}/statement/summary |
client.customer.info() |
GET {prefix}/jp/v2/customer-info |
client.request(method, path) |
произвольный запрос (escape hatch) |
Вендоренные OpenAPI-спеки банка и реалистичные моки: specs/alfa-api/.
Лицензия
MIT
Metadata
Release files for alfabank-sdk 1.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| alfabank_sdk-1.0.3.tar.gz | 93.5 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| alfabank_sdk-1.0.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 118.6 kB
Release files / alfabank_sdk-1.0.3.tar.gz
| Download URL | alfabank_sdk-1.0.3.tar.gz |
|---|---|
| Size | 93.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
46911ac44a8bfd2b3be33663067bf070047e45882bae45cfc08f58325c1cec45
|
|
BLAKE2b-256 checksum How to use checksums |
e4444ea42ef3f520c7d5a0d536119afd66f3b8c6dcda59c900820c99518f0f71
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
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 Jul 18, 2026.
Transparency logRelease files / alfabank_sdk-1.0.3-py3-none-any.whl
| Download URL | alfabank_sdk-1.0.3-py3-none-any.whl |
|---|---|
| Size | 25.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b9102056b887f57b6d49898eaa319aca450800c5191a7086f1955ec8b81274fb
|
|
BLAKE2b-256 checksum How to use checksums |
53d5694ccf5054ba6178b8afec34ead7db9abda7afb24e5ca80bb84f9d1218f0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.12
|
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 Jul 18, 2026.
Transparency log