Skip to main content

Unofficial async Python SDK for the Alfa-Bank Alfa API (h2h): statements, turnover summary, customer info

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

alfabank_sdk-1.0.2.tar.gz (93.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

alfabank_sdk-1.0.2-py3-none-any.whl (25.1 kB view details)

Uploaded Python 3

File details

Details for the file alfabank_sdk-1.0.2.tar.gz.

File metadata

  • Download URL: alfabank_sdk-1.0.2.tar.gz
  • Upload date:
  • Size: 93.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for alfabank_sdk-1.0.2.tar.gz
Algorithm Hash digest
SHA256 3187f0e213926b6fc916252d64f654018f9d43cdc825ef87a19e5d9427a448f8
MD5 c333ed30eab4d1e6518dfb3f5900d160
BLAKE2b-256 74dbac0384187235ad36dac75e80e02a0cee10c1ab5c08f11eddbd7bbca8e33a

See more details on using hashes here.

Provenance

The following attestation bundles were made for alfabank_sdk-1.0.2.tar.gz:

Publisher: publish.yml on IceOne-i/alfabank-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file alfabank_sdk-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: alfabank_sdk-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 25.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for alfabank_sdk-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 acb5091fd17554d54176b8d51fe57915ccf765d92933541b7ac6ac045c80025b
MD5 a9a59c87eac2277e2e171c574e339c68
BLAKE2b-256 0a7e2cdd5914f12ed0e9c2e09ef70d9e3586dcf1c0fa62b4010f0c92703f38c1

See more details on using hashes here.

Provenance

The following attestation bundles were made for alfabank_sdk-1.0.2-py3-none-any.whl:

Publisher: publish.yml on IceOne-i/alfabank-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page