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.3.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.3-py3-none-any.whl (25.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: alfabank_sdk-1.0.3.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.3.tar.gz
Algorithm Hash digest
SHA256 46911ac44a8bfd2b3be33663067bf070047e45882bae45cfc08f58325c1cec45
MD5 d8b07b89aee19cf825fefcb3072238d6
BLAKE2b-256 e4444ea42ef3f520c7d5a0d536119afd66f3b8c6dcda59c900820c99518f0f71

See more details on using hashes here.

Provenance

The following attestation bundles were made for alfabank_sdk-1.0.3.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.3-py3-none-any.whl.

File metadata

  • Download URL: alfabank_sdk-1.0.3-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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 b9102056b887f57b6d49898eaa319aca450800c5191a7086f1955ec8b81274fb
MD5 db74adb332b311cd79f1761afad9d104
BLAKE2b-256 53d5694ccf5054ba6178b8afec34ead7db9abda7afb24e5ca80bb84f9d1218f0

See more details on using hashes here.

Provenance

The following attestation bundles were made for alfabank_sdk-1.0.3-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