Skip to main content

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

Установка

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.1.tar.gz (92.7 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.1-py3-none-any.whl (24.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: alfabank_sdk-1.0.1.tar.gz
  • Upload date:
  • Size: 92.7 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.1.tar.gz
Algorithm Hash digest
SHA256 39e9ef0a444a46d8ef6ff722e1ee19a53ab6f4b6b348671a89e5d2055495c776
MD5 cb63d58662c58736b5402b804ba6498c
BLAKE2b-256 a1fda662bf33d7f5f524d2d53623eee0816d99d339825a24b61a855f568e55f9

See more details on using hashes here.

Provenance

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

File metadata

  • Download URL: alfabank_sdk-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 24.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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 353457276e4cb9c62976ff1fbf418e07dfc8b6eeb5127696d679c803a034aee9
MD5 60cf1159675ab6a130380110c4215c98
BLAKE2b-256 af6556e3a71f53e67b097d50995ab06b0b68da95b05ae625084dab3a4b12b7a4

See more details on using hashes here.

Provenance

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