fastapi-app-builder 0.1.0b1__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.
@@ -0,0 +1,73 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual environments
24
+ venv/
25
+ .venv/
26
+ ENV/
27
+ env/
28
+ venvs/
29
+ .envs/
30
+ .virtualenv/
31
+ .pyenv/
32
+ pythonenv/
33
+ Pipfile.lock
34
+ poetry.lock
35
+
36
+ # Environment variables
37
+ .env
38
+ .env.*
39
+ !.env.example
40
+
41
+ # IDE
42
+ .idea/
43
+ .vscode/
44
+ *.swp
45
+ *.swo
46
+ *~
47
+
48
+ # Testing
49
+ .pytest_cache/
50
+ .coverage
51
+ htmlcov/
52
+ .tox/
53
+ .nox/
54
+
55
+ # mypy
56
+ .mypy_cache/
57
+
58
+ # ruff
59
+ .ruff_cache/
60
+
61
+ # Distribution
62
+ *.manifest
63
+ *.spec
64
+
65
+ # Logs
66
+ *.log
67
+
68
+ # OS
69
+ .DS_Store
70
+ Thumbs.db
71
+
72
+ # Claude Code
73
+ .claude/
@@ -0,0 +1,52 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0b1] - 2025-01-20
9
+
10
+ ### Changed
11
+ - **Breaking:** Renamed package from `fastapi-builder` to `fastapi-app-builder`
12
+ - **Breaking:** Renamed import from `fastapi_builder` to `fastapi_app_builder`
13
+
14
+ ### Added
15
+ - `py.typed` marker for PEP 561 type checking support
16
+
17
+ ### Migration
18
+ ```python
19
+ # Before
20
+ from fastapi_builder import AppBuilder
21
+
22
+ # After
23
+ from fastapi_app_builder import AppBuilder
24
+ ```
25
+
26
+ ## [0.1.0a3] - 2025-01-19
27
+
28
+ ### Fixed
29
+ - Resolved mypy strict mode errors
30
+ - Ruff linting fixes
31
+
32
+ ## [0.1.0a2] - 2025-01-18
33
+
34
+ ### Fixed
35
+ - Pre-release fixes and improvements
36
+
37
+ ## [0.1.0a1] - 2025-01-17
38
+
39
+ ### Added
40
+ - Initial alpha release
41
+ - `AppBuilder` for configuring FastAPI applications
42
+ - `Services` container for dependency injection
43
+ - Service lifetimes: Singleton, Scoped, Transient
44
+ - Factory registration with `add_*_factory()` methods
45
+ - `resolve()` function for service resolution anywhere in code
46
+ - Automatic constructor injection
47
+ - Startup validation for missing dependencies
48
+ - `extend()` method to add DI to existing FastAPI apps
49
+ - CORS installer via `install_cors()`
50
+ - SQLAlchemy integration support
51
+ - `InjectableRouter` (optional, standard `APIRouter` works)
52
+ - Installer pattern for modular service registration
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Jan Klečka
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,364 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-app-builder
3
+ Version: 0.1.0b1
4
+ Summary: ASP.NET Core-style dependency injection for FastAPI
5
+ Project-URL: Homepage, https://github.com/Saurus119/fastapi-builder
6
+ Project-URL: Documentation, https://github.com/Saurus119/fastapi-builder#readme
7
+ Project-URL: Repository, https://github.com/Saurus119/fastapi-builder
8
+ Project-URL: Issues, https://github.com/Saurus119/fastapi-builder/issues
9
+ Author-email: Jan Klečka <jan.klecka12@gmail.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: asp.net,dependency-injection,di,dotnet,fastapi,ioc
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: fastapi>=0.100.0
26
+ Provides-Extra: all
27
+ Requires-Dist: sqlalchemy>=2.0.0; extra == 'all'
28
+ Provides-Extra: dev
29
+ Requires-Dist: coverage>=7.0.0; extra == 'dev'
30
+ Requires-Dist: httpx>=0.27.0; extra == 'dev'
31
+ Requires-Dist: mypy>=1.9.0; extra == 'dev'
32
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
33
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
34
+ Requires-Dist: ruff>=0.8.0; extra == 'dev'
35
+ Provides-Extra: sqlalchemy
36
+ Requires-Dist: sqlalchemy>=2.0.0; extra == 'sqlalchemy'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # fastapi-app-builder
40
+
41
+ [![PyPI version](https://img.shields.io/pypi/v/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
42
+ [![Python versions](https://img.shields.io/pypi/pyversions/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
43
+ [![Downloads](https://static.pepy.tech/badge/fastapi-app-builder)](https://pepy.tech/project/fastapi-app-builder)
44
+ [![License](https://img.shields.io/pypi/l/fastapi-app-builder.svg)](https://github.com/Saurus119/fastapi-app-builder/blob/main/LICENSE)
45
+
46
+ [![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20A%20Coffee-support-yellow.svg?style=flat&logo=buy-me-a-coffee)](https://buymeacoffee.com/saurus119)
47
+
48
+ ASP.NET Core-style dependency injection for FastAPI - clean controllers, builder pattern, zero boilerplate.
49
+
50
+ ## Features
51
+
52
+ - **Clean controllers** - No `Depends()`, `Injected[]`, or `Provide[]` - just type hints
53
+ - **Standard FastAPI** - Use standard `APIRouter` - no custom router classes needed
54
+ - **Builder pattern** - Familiar `AppBuilder` for application configuration
55
+ - **Proper lifetimes** - Singleton, Scoped (per-request), and Transient
56
+ - **Fail fast** - Validate all dependencies at startup
57
+ - **Familiar API** - Mirror .NET naming conventions
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install fastapi-app-builder
63
+ ```
64
+
65
+ With SQLAlchemy support:
66
+ ```bash
67
+ pip install fastapi-app-builder[sqlalchemy]
68
+ ```
69
+
70
+ ## Quick Start
71
+
72
+ ```python
73
+ from typing import Protocol
74
+ from fastapi import APIRouter
75
+ from fastapi_app_builder import AppBuilder
76
+
77
+ # Define your service interface and implementation
78
+ class IGreetingService(Protocol):
79
+ def greet(self, name: str) -> str: ...
80
+
81
+ class GreetingService:
82
+ def greet(self, name: str) -> str:
83
+ return f"Hello, {name}!"
84
+
85
+ # Create router with clean dependency injection - no Depends() needed!
86
+ router = APIRouter(prefix="/greetings")
87
+
88
+ @router.get("/{name}")
89
+ async def greet(name: str, greeting_service: IGreetingService):
90
+ return {"message": greeting_service.greet(name)}
91
+
92
+ # Configure and build the application
93
+ builder = AppBuilder()
94
+ builder.services.add_singleton(IGreetingService, GreetingService)
95
+ builder.add_controller(router)
96
+ app = builder.build()
97
+ ```
98
+
99
+ ## Using Standard APIRouter
100
+
101
+ Use FastAPI's standard `APIRouter` - the dependency injection works automatically. Routers can be defined in separate files and imported in any order:
102
+
103
+ ```python
104
+ # controllers/users.py
105
+ from fastapi import APIRouter
106
+ from services import IUserService
107
+
108
+ router = APIRouter(prefix="/users", tags=["Users"])
109
+
110
+ @router.get("/{user_id}")
111
+ async def get_user(user_id: int, user_service: IUserService):
112
+ # user_service is automatically injected - no Depends() needed!
113
+ return user_service.get_user(user_id)
114
+
115
+ @router.post("/")
116
+ async def create_user(data: CreateUserDto, user_service: IUserService):
117
+ return user_service.create(data)
118
+ ```
119
+
120
+ ```python
121
+ # main.py
122
+ from fastapi_app_builder import AppBuilder
123
+ from controllers.users import router as user_router
124
+ from services import IUserRepository, UserRepository, IUserService, UserService
125
+
126
+ builder = AppBuilder()
127
+ builder.services.add_scoped(IUserRepository, UserRepository)
128
+ builder.services.add_scoped(IUserService, UserService)
129
+ builder.add_controller(user_router)
130
+ app = builder.build()
131
+ ```
132
+
133
+ ## Service Lifetimes
134
+
135
+ ### Singleton
136
+ One instance shared across the entire application:
137
+ ```python
138
+ builder.services.add_singleton(IMyService, MyService)
139
+ ```
140
+
141
+ ### Scoped
142
+ One instance per HTTP request:
143
+ ```python
144
+ builder.services.add_scoped(IMyService, MyService)
145
+ ```
146
+
147
+ ### Transient
148
+ New instance every time it's requested:
149
+ ```python
150
+ builder.services.add_transient(IMyService, MyService)
151
+ ```
152
+
153
+ ## Factory Registration
154
+
155
+ Register services with custom factory functions:
156
+ ```python
157
+ builder.services.add_singleton_factory(IMyService, lambda: MyService(config))
158
+ builder.services.add_scoped_factory(IMyService, create_my_service)
159
+ ```
160
+
161
+ ## Nested Dependencies
162
+
163
+ Dependencies are automatically resolved via constructor injection:
164
+ ```python
165
+ class UserRepository:
166
+ pass
167
+
168
+ class UserService:
169
+ def __init__(self, user_repository: UserRepository):
170
+ self.repo = user_repository
171
+
172
+ builder.services.add_scoped(UserRepository)
173
+ builder.services.add_scoped(UserService)
174
+ # UserService will automatically receive UserRepository
175
+ ```
176
+
177
+ ## Resolving Services Anywhere
178
+
179
+ Use `resolve()` to get services from anywhere in your code during a request:
180
+
181
+ ```python
182
+ from fastapi_app_builder import resolve
183
+
184
+ class OrderService:
185
+ def create_order(self, items: list):
186
+ # Resolve services on-demand (not just in constructors)
187
+ inventory = resolve(IInventoryService)
188
+ payment = resolve(IPaymentService)
189
+
190
+ for item in items:
191
+ inventory.reserve(item)
192
+
193
+ return payment.charge(items)
194
+
195
+ # Also works in utility functions
196
+ def get_current_user():
197
+ auth = resolve(IAuthService)
198
+ return auth.get_current_user()
199
+ ```
200
+
201
+ Note: Prefer constructor injection when possible - it makes dependencies explicit and easier to test.
202
+
203
+ ## Installer Pattern
204
+
205
+ Organize service registrations with installers for better modularity:
206
+
207
+ ```python
208
+ # installers/repositories.py
209
+ from fastapi_app_builder import Services
210
+
211
+ def install_repositories(services: Services) -> None:
212
+ services.add_scoped(IUserRepository, UserRepository)
213
+ services.add_scoped(IProductRepository, ProductRepository)
214
+
215
+ # installers/services.py
216
+ def install_services(services: Services) -> None:
217
+ services.add_scoped(IUserService, UserService)
218
+ services.add_scoped(IProductService, ProductService)
219
+
220
+ # main.py
221
+ builder = AppBuilder()
222
+ builder.services.install(install_repositories).install(install_services)
223
+ ```
224
+
225
+ You can also use `builder.install()` if you need access to the full builder:
226
+ ```python
227
+ def install_all(builder: AppBuilder) -> None:
228
+ builder.services.add_scoped(IUserRepository, UserRepository)
229
+ builder.with_title("My API")
230
+
231
+ builder.install(install_all)
232
+ ```
233
+
234
+ ## Configuration
235
+
236
+ ```python
237
+ builder = AppBuilder()
238
+
239
+ # Configure OpenAPI docs
240
+ builder.with_title("My API")
241
+ builder.with_version("1.0.0")
242
+ builder.with_description("My awesome API")
243
+ builder.with_docs_url("/swagger")
244
+
245
+ # Configure CORS
246
+ builder.install_cors(
247
+ origins=["http://localhost:3000"],
248
+ allow_credentials=True,
249
+ )
250
+
251
+ # Disable validation (not recommended)
252
+ builder.with_validation(False)
253
+ ```
254
+
255
+ ## Validation
256
+
257
+ By default, all dependencies are validated at startup:
258
+ ```python
259
+ builder.services.add_scoped(IUserService, UserService)
260
+ # If UserService depends on IUserRepository which isn't registered,
261
+ # builder.build() will raise ValidationError
262
+ ```
263
+
264
+ ## Extending an Existing FastAPI App
265
+
266
+ Use `extend()` to add DI to an existing FastAPI app:
267
+
268
+ ```python
269
+ from fastapi import FastAPI
270
+ from fastapi_app_builder import AppBuilder
271
+ from controllers import user_router
272
+
273
+ # Create your own FastAPI instance with custom settings
274
+ app = FastAPI(
275
+ title="My API",
276
+ lifespan=my_lifespan, # Custom lifespan handler
277
+ )
278
+
279
+ # Add routes directly
280
+ @app.get("/health")
281
+ async def health():
282
+ return {"status": "ok"}
283
+
284
+ # Use builder for DI only
285
+ builder = AppBuilder()
286
+ builder.services.add_scoped(IUserService, UserService)
287
+ builder.add_controller(user_router)
288
+ builder.extend(app) # Adds DI to existing app
289
+ ```
290
+
291
+ ## SQLAlchemy Integration
292
+
293
+ ```python
294
+ from sqlalchemy import create_engine
295
+ from sqlalchemy.orm import Session, sessionmaker
296
+ from fastapi_app_builder import AppBuilder
297
+
298
+ engine = create_engine("sqlite:///./app.db")
299
+ SessionLocal = sessionmaker(bind=engine)
300
+
301
+ def install_database(builder: AppBuilder) -> None:
302
+ # Use dispose to automatically close sessions after each request
303
+ builder.services.add_scoped_factory(
304
+ Session,
305
+ factory=SessionLocal,
306
+ dispose=lambda s: s.close()
307
+ )
308
+
309
+ builder = AppBuilder()
310
+ builder.install(install_database)
311
+ ```
312
+
313
+ The `dispose` parameter ensures resources are properly cleaned up when the request ends, even if an exception occurs.
314
+
315
+ ## API Reference
316
+
317
+ ### AppBuilder
318
+
319
+ The main entry point for configuring your FastAPI application.
320
+
321
+ | Method | Description |
322
+ |--------|-------------|
323
+ | `services` | Property to access the DI container |
324
+ | `add_controller(router)` | Add a standard FastAPI `APIRouter` to the application |
325
+ | `install(installer)` | Apply an installer function |
326
+ | `install_cors(origins, ...)` | Configure CORS middleware |
327
+ | `with_title(title)` | Set application title |
328
+ | `with_version(version)` | Set application version |
329
+ | `with_description(desc)` | Set application description |
330
+ | `with_docs_url(url)` | Set Swagger UI URL |
331
+ | `with_validation(enabled)` | Enable/disable startup validation |
332
+ | `build()` | Build and return a new FastAPI app |
333
+ | `extend(app)` | Add DI to an existing FastAPI app |
334
+
335
+ ### Services
336
+
337
+ The dependency injection container.
338
+
339
+ | Method | Description |
340
+ |--------|-------------|
341
+ | `add_singleton(interface, impl)` | Register a singleton service |
342
+ | `add_scoped(interface, impl)` | Register a scoped service |
343
+ | `add_transient(interface, impl)` | Register a transient service |
344
+ | `add_singleton_factory(interface, factory)` | Register singleton with factory |
345
+ | `add_scoped_factory(interface, factory, dispose=None)` | Register scoped with factory and optional cleanup |
346
+ | `add_transient_factory(interface, factory)` | Register transient with factory |
347
+ | `install(installer)` | Apply an installer function to register services |
348
+ | `is_registered(interface)` | Check if a service is registered |
349
+ | `resolve(interface)` | Manually resolve a service |
350
+ | `validate()` | Validate all registrations |
351
+
352
+ ### resolve()
353
+
354
+ Resolve a service from anywhere during a request:
355
+
356
+ ```python
357
+ from fastapi_app_builder import resolve
358
+
359
+ service = resolve(IMyService)
360
+ ```
361
+
362
+ ## License
363
+
364
+ MIT