alfabank-sdk 1.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. alfabank_sdk-1.0.1/.gitattributes +2 -0
  2. alfabank_sdk-1.0.1/.github/workflows/publish.yml +37 -0
  3. alfabank_sdk-1.0.1/.github/workflows/tests.yml +36 -0
  4. alfabank_sdk-1.0.1/.gitignore +26 -0
  5. alfabank_sdk-1.0.1/CHANGELOG.md +10 -0
  6. alfabank_sdk-1.0.1/LICENSE +21 -0
  7. alfabank_sdk-1.0.1/PKG-INFO +136 -0
  8. alfabank_sdk-1.0.1/README.md +107 -0
  9. alfabank_sdk-1.0.1/docs/superpowers/plans/2026-07-12-alfabank-sdk.md +4055 -0
  10. alfabank_sdk-1.0.1/docs/superpowers/specs/2026-07-12-alfabank-sdk-design.md +299 -0
  11. alfabank_sdk-1.0.1/examples/basic_usage.py +29 -0
  12. alfabank_sdk-1.0.1/examples/fastapi_integration.py +37 -0
  13. alfabank_sdk-1.0.1/pyproject.toml +72 -0
  14. alfabank_sdk-1.0.1/specs/alfa-api/customer-info/customer-info-v2.yaml +7 -0
  15. alfabank_sdk-1.0.1/specs/alfa-api/customer-info/v2/paths/customer-info.yaml +97 -0
  16. alfabank_sdk-1.0.1/specs/alfa-api/customer-info/v2/schemas/customer-info.yaml +300 -0
  17. alfabank_sdk-1.0.1/specs/alfa-api/customer-info/v2/schemas/errors.yaml +91 -0
  18. alfabank_sdk-1.0.1/specs/alfa-api/digital-ruble/digital-ruble.yaml +420 -0
  19. alfabank_sdk-1.0.1/specs/alfa-api/mocks/customer-info/customer-info-v2.json +109 -0
  20. alfabank_sdk-1.0.1/specs/alfa-api/mocks/digital-ruble/certificates.json +17 -0
  21. alfabank_sdk-1.0.1/specs/alfa-api/mocks/digital-ruble/statement-response.json +32 -0
  22. alfabank_sdk-1.0.1/specs/alfa-api/mocks/digital-ruble/wallet-context.json +12 -0
  23. alfabank_sdk-1.0.1/specs/alfa-api/mocks/transactions/statement-1c.xml +112 -0
  24. alfabank_sdk-1.0.1/specs/alfa-api/mocks/transactions/statement-mt940.txt +11 -0
  25. alfabank_sdk-1.0.1/specs/alfa-api/mocks/transactions/statement-summary.json +40 -0
  26. alfabank_sdk-1.0.1/specs/alfa-api/mocks/transactions/statement.json +178 -0
  27. alfabank_sdk-1.0.1/specs/alfa-api/transactions/statement.yaml +1780 -0
  28. alfabank_sdk-1.0.1/specs/alfa-api/transactions/statement1c.yaml +1050 -0
  29. alfabank_sdk-1.0.1/specs/alfa-api/transactions/summary.yaml +310 -0
  30. alfabank_sdk-1.0.1/src/alfabank/__init__.py +107 -0
  31. alfabank_sdk-1.0.1/src/alfabank/_transport.py +224 -0
  32. alfabank_sdk-1.0.1/src/alfabank/_utils.py +48 -0
  33. alfabank_sdk-1.0.1/src/alfabank/_version.py +24 -0
  34. alfabank_sdk-1.0.1/src/alfabank/auth.py +59 -0
  35. alfabank_sdk-1.0.1/src/alfabank/client.py +116 -0
  36. alfabank_sdk-1.0.1/src/alfabank/enums.py +112 -0
  37. alfabank_sdk-1.0.1/src/alfabank/exceptions.py +178 -0
  38. alfabank_sdk-1.0.1/src/alfabank/models/__init__.py +43 -0
  39. alfabank_sdk-1.0.1/src/alfabank/models/common.py +46 -0
  40. alfabank_sdk-1.0.1/src/alfabank/models/customer.py +109 -0
  41. alfabank_sdk-1.0.1/src/alfabank/models/statement.py +208 -0
  42. alfabank_sdk-1.0.1/src/alfabank/oauth.py +165 -0
  43. alfabank_sdk-1.0.1/src/alfabank/py.typed +0 -0
  44. alfabank_sdk-1.0.1/src/alfabank/resources/__init__.py +6 -0
  45. alfabank_sdk-1.0.1/src/alfabank/resources/_base.py +14 -0
  46. alfabank_sdk-1.0.1/src/alfabank/resources/customer.py +17 -0
  47. alfabank_sdk-1.0.1/src/alfabank/resources/statements.py +97 -0
  48. alfabank_sdk-1.0.1/tests/__init__.py +0 -0
  49. alfabank_sdk-1.0.1/tests/conftest.py +47 -0
  50. alfabank_sdk-1.0.1/tests/test_auth.py +47 -0
  51. alfabank_sdk-1.0.1/tests/test_client.py +108 -0
  52. alfabank_sdk-1.0.1/tests/test_customer_resource.py +47 -0
  53. alfabank_sdk-1.0.1/tests/test_enums.py +44 -0
  54. alfabank_sdk-1.0.1/tests/test_exceptions.py +123 -0
  55. alfabank_sdk-1.0.1/tests/test_models_common.py +39 -0
  56. alfabank_sdk-1.0.1/tests/test_models_customer.py +79 -0
  57. alfabank_sdk-1.0.1/tests/test_models_statement.py +124 -0
  58. alfabank_sdk-1.0.1/tests/test_oauth.py +136 -0
  59. alfabank_sdk-1.0.1/tests/test_package.py +10 -0
  60. alfabank_sdk-1.0.1/tests/test_public_api.py +70 -0
  61. alfabank_sdk-1.0.1/tests/test_retry_policy.py +94 -0
  62. alfabank_sdk-1.0.1/tests/test_statements_resource.py +146 -0
  63. alfabank_sdk-1.0.1/tests/test_transport.py +145 -0
  64. alfabank_sdk-1.0.1/tests/test_utils.py +45 -0
@@ -0,0 +1,2 @@
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
@@ -0,0 +1,37 @@
1
+ name: publish
2
+
3
+ on:
4
+ push:
5
+ tags: ["v*"]
6
+
7
+ jobs:
8
+ build:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ with:
13
+ fetch-depth: 0
14
+ - uses: actions/setup-python@v5
15
+ with:
16
+ python-version: "3.12"
17
+ - name: Build distributions
18
+ run: |
19
+ python -m pip install --upgrade pip build
20
+ python -m build
21
+ - uses: actions/upload-artifact@v4
22
+ with:
23
+ name: dist
24
+ path: dist/
25
+
26
+ publish:
27
+ needs: build
28
+ runs-on: ubuntu-latest
29
+ environment: pypi
30
+ permissions:
31
+ id-token: write # PyPI Trusted Publishing
32
+ steps:
33
+ - uses: actions/download-artifact@v4
34
+ with:
35
+ name: dist
36
+ path: dist/
37
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,36 @@
1
+ name: tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ strategy:
11
+ fail-fast: false
12
+ matrix:
13
+ os: [ubuntu-latest]
14
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
15
+ include:
16
+ - os: windows-latest
17
+ python-version: "3.12"
18
+ runs-on: ${{ matrix.os }}
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ with:
22
+ fetch-depth: 0 # hatch-vcs needs tags
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: ${{ matrix.python-version }}
26
+ cache: pip
27
+ - name: Install
28
+ run: |
29
+ python -m pip install --upgrade pip
30
+ pip install -e ".[dev]"
31
+ - name: Ruff
32
+ run: python -m ruff check src tests examples
33
+ - name: Mypy
34
+ run: python -m mypy src/alfabank
35
+ - name: Pytest
36
+ run: python -m pytest --cov=alfabank --cov-report=term-missing
@@ -0,0 +1,26 @@
1
+ # IDE
2
+ .idea/
3
+ .vscode/
4
+
5
+ # Python
6
+ __pycache__/
7
+ *.py[cod]
8
+ *.egg-info/
9
+ dist/
10
+ build/
11
+ .venv/
12
+ venv/
13
+
14
+ # Generated by hatch-vcs
15
+ src/alfabank/_version.py
16
+
17
+ # SDD process scratch (task briefs, reports, progress ledger)
18
+ .superpowers/
19
+
20
+ # Tooling caches
21
+ .pytest_cache/
22
+ .ruff_cache/
23
+ .mypy_cache/
24
+ .coverage
25
+ htmlcov/
26
+ docs/bank-support-reply.md
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ### Added
6
+ - `AlfaBankClient` — async-клиент Alfa API (h2h): выписки, сводка оборотов, customer-info.
7
+ - Две схемы аутентификации (`ApiKey`, `Bearer`) + `token_provider` для внешнего управления токенами.
8
+ - Экспериментальный модуль `alfabank.oauth` (обмен кода, refresh, кэширующий провайдер).
9
+ - Идемпотентные ретраи с backoff, опциональный rate limiter, маппинг ошибок API.
10
+ - Модели pydantic v2 с `Decimal` для денежных сумм; проверены на моках банка.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nikita Belan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: alfabank-sdk
3
+ Version: 1.0.1
4
+ Summary: Async Python SDK for the Alfa-Bank Alfa API (h2h): statements, turnover summary, customer info
5
+ Author: Nikita Belan
6
+ License: MIT
7
+ License-File: LICENSE
8
+ Keywords: alfa-api,alfabank,async,bank,sdk,statements
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: httpx>=0.25
20
+ Requires-Dist: pydantic>=2.5
21
+ Provides-Extra: dev
22
+ Requires-Dist: mypy; extra == 'dev'
23
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
24
+ Requires-Dist: pytest-cov; extra == 'dev'
25
+ Requires-Dist: pytest>=8; extra == 'dev'
26
+ Requires-Dist: respx>=0.21; extra == 'dev'
27
+ Requires-Dist: ruff; extra == 'dev'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # alfabank-sdk
31
+
32
+ Асинхронный Python SDK для **Alfa API** Альфа-Банка (интеграция host-to-host):
33
+ выписки по счетам, сводка оборотов, информация об организации и её счетах.
34
+
35
+ - Python >= 3.10, полностью async (httpx), строгая типизация (pydantic v2, `py.typed`)
36
+ - Деньги — `Decimal`, никаких float
37
+ - Ретраи с учётом идемпотентности, опциональный rate limiter
38
+ - Две схемы аутентификации банка: `ApiKey` и `Bearer` + шов `token_provider` под OAuth
39
+
40
+ ## Установка
41
+
42
+ ```bash
43
+ pip install alfabank-sdk
44
+ ```
45
+
46
+ ## Быстрый старт
47
+
48
+ ```python
49
+ import asyncio
50
+ from datetime import date
51
+
52
+ from alfabank import AlfaBankClient
53
+
54
+
55
+ async def main() -> None:
56
+ async with AlfaBankClient(api_key="ВАШ_КЛЮЧ") as client:
57
+ # Профиль организации и счета с балансами
58
+ info = await client.customer.info()
59
+ for account in info.accounts:
60
+ print(account.number, account.amount_balance)
61
+
62
+ # Выписка за дату (автопагинация)
63
+ async for tx in client.statements.iter_transactions(
64
+ "40702810102300000001", date(2026, 7, 1)
65
+ ):
66
+ print(tx.direction, tx.amount.amount if tx.amount else None, tx.payment_purpose)
67
+
68
+ # Сводка оборотов
69
+ summary = await client.statements.summary("40702810102300000001", date(2026, 7, 1))
70
+ print(summary.closing_balance)
71
+
72
+
73
+ asyncio.run(main())
74
+ ```
75
+
76
+ ## Аутентификация
77
+
78
+ Ровно один из трёх способов:
79
+
80
+ ```python
81
+ AlfaBankClient(api_key="...") # Authorization: ApiKey <key>
82
+ AlfaBankClient(access_token="...") # Authorization: Bearer <token>
83
+ AlfaBankClient(token_provider=provider) # (a)sync callable -> значение заголовка
84
+ ```
85
+
86
+ OAuth-хелпер (**experimental** — контракт /oidc/token не проверен на живой песочнице):
87
+
88
+ ```python
89
+ from alfabank.oauth import OAuthTokenProvider
90
+
91
+ provider = OAuthTokenProvider(
92
+ client_id="...", client_secret="...", refresh_token="...",
93
+ )
94
+ client = AlfaBankClient(token_provider=provider)
95
+ ```
96
+
97
+ ## Песочница и настройка окружения
98
+
99
+ ```python
100
+ from alfabank import SANDBOX_BASE_URL, AlfaBankClient
101
+
102
+ client = AlfaBankClient(api_key="...", base_url=SANDBOX_BASE_URL)
103
+ ```
104
+
105
+ `base_url` и `api_prefix` настраиваются: шлюзовые пути могут отличаться
106
+ в зависимости от договора с банком. mTLS — через параметры `cert`/`verify`
107
+ (PEM) или инъекцию своего `httpx.AsyncClient` в `http_client=`.
108
+
109
+ ## Обработка ошибок
110
+
111
+ ```python
112
+ from alfabank import AlfaBankAPIError, AlfaBankRateLimitError
113
+
114
+ try:
115
+ page = await client.statements.transactions("40702810102300000001", "2026-07-01")
116
+ except AlfaBankRateLimitError as exc:
117
+ print("Лимит запросов, повторить через:", exc.retry_after)
118
+ except AlfaBankAPIError as exc:
119
+ print(exc.status_code, exc.error_code, exc.request_id, exc.response_body)
120
+ ```
121
+
122
+ ## Эндпоинты
123
+
124
+ | Метод SDK | HTTP |
125
+ |---|---|
126
+ | `client.statements.transactions()` | `GET {prefix}/statement/transactions` |
127
+ | `client.statements.iter_transactions()` | автопагинация по `_links rel=next` |
128
+ | `client.statements.summary()` | `GET {prefix}/statement/summary` |
129
+ | `client.customer.info()` | `GET {prefix}/jp/v2/customer-info` |
130
+ | `client.request(method, path)` | произвольный запрос (escape hatch) |
131
+
132
+ Вендоренные OpenAPI-спеки банка и реалистичные моки: `specs/alfa-api/`.
133
+
134
+ ## Лицензия
135
+
136
+ MIT
@@ -0,0 +1,107 @@
1
+ # alfabank-sdk
2
+
3
+ Асинхронный Python SDK для **Alfa API** Альфа-Банка (интеграция host-to-host):
4
+ выписки по счетам, сводка оборотов, информация об организации и её счетах.
5
+
6
+ - Python >= 3.10, полностью async (httpx), строгая типизация (pydantic v2, `py.typed`)
7
+ - Деньги — `Decimal`, никаких float
8
+ - Ретраи с учётом идемпотентности, опциональный rate limiter
9
+ - Две схемы аутентификации банка: `ApiKey` и `Bearer` + шов `token_provider` под OAuth
10
+
11
+ ## Установка
12
+
13
+ ```bash
14
+ pip install alfabank-sdk
15
+ ```
16
+
17
+ ## Быстрый старт
18
+
19
+ ```python
20
+ import asyncio
21
+ from datetime import date
22
+
23
+ from alfabank import AlfaBankClient
24
+
25
+
26
+ async def main() -> None:
27
+ async with AlfaBankClient(api_key="ВАШ_КЛЮЧ") as client:
28
+ # Профиль организации и счета с балансами
29
+ info = await client.customer.info()
30
+ for account in info.accounts:
31
+ print(account.number, account.amount_balance)
32
+
33
+ # Выписка за дату (автопагинация)
34
+ async for tx in client.statements.iter_transactions(
35
+ "40702810102300000001", date(2026, 7, 1)
36
+ ):
37
+ print(tx.direction, tx.amount.amount if tx.amount else None, tx.payment_purpose)
38
+
39
+ # Сводка оборотов
40
+ summary = await client.statements.summary("40702810102300000001", date(2026, 7, 1))
41
+ print(summary.closing_balance)
42
+
43
+
44
+ asyncio.run(main())
45
+ ```
46
+
47
+ ## Аутентификация
48
+
49
+ Ровно один из трёх способов:
50
+
51
+ ```python
52
+ AlfaBankClient(api_key="...") # Authorization: ApiKey <key>
53
+ AlfaBankClient(access_token="...") # Authorization: Bearer <token>
54
+ AlfaBankClient(token_provider=provider) # (a)sync callable -> значение заголовка
55
+ ```
56
+
57
+ OAuth-хелпер (**experimental** — контракт /oidc/token не проверен на живой песочнице):
58
+
59
+ ```python
60
+ from alfabank.oauth import OAuthTokenProvider
61
+
62
+ provider = OAuthTokenProvider(
63
+ client_id="...", client_secret="...", refresh_token="...",
64
+ )
65
+ client = AlfaBankClient(token_provider=provider)
66
+ ```
67
+
68
+ ## Песочница и настройка окружения
69
+
70
+ ```python
71
+ from alfabank import SANDBOX_BASE_URL, AlfaBankClient
72
+
73
+ client = AlfaBankClient(api_key="...", base_url=SANDBOX_BASE_URL)
74
+ ```
75
+
76
+ `base_url` и `api_prefix` настраиваются: шлюзовые пути могут отличаться
77
+ в зависимости от договора с банком. mTLS — через параметры `cert`/`verify`
78
+ (PEM) или инъекцию своего `httpx.AsyncClient` в `http_client=`.
79
+
80
+ ## Обработка ошибок
81
+
82
+ ```python
83
+ from alfabank import AlfaBankAPIError, AlfaBankRateLimitError
84
+
85
+ try:
86
+ page = await client.statements.transactions("40702810102300000001", "2026-07-01")
87
+ except AlfaBankRateLimitError as exc:
88
+ print("Лимит запросов, повторить через:", exc.retry_after)
89
+ except AlfaBankAPIError as exc:
90
+ print(exc.status_code, exc.error_code, exc.request_id, exc.response_body)
91
+ ```
92
+
93
+ ## Эндпоинты
94
+
95
+ | Метод SDK | HTTP |
96
+ |---|---|
97
+ | `client.statements.transactions()` | `GET {prefix}/statement/transactions` |
98
+ | `client.statements.iter_transactions()` | автопагинация по `_links rel=next` |
99
+ | `client.statements.summary()` | `GET {prefix}/statement/summary` |
100
+ | `client.customer.info()` | `GET {prefix}/jp/v2/customer-info` |
101
+ | `client.request(method, path)` | произвольный запрос (escape hatch) |
102
+
103
+ Вендоренные OpenAPI-спеки банка и реалистичные моки: `specs/alfa-api/`.
104
+
105
+ ## Лицензия
106
+
107
+ MIT