fastapi-app-builder 0.1.0b1__tar.gz → 0.1.0b2__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 (28) hide show
  1. fastapi_app_builder-0.1.0b2/CHANGELOG.md +115 -0
  2. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/PKG-INFO +104 -19
  3. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/README.md +100 -17
  4. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/pyproject.toml +4 -1
  5. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/__init__.py +1 -1
  6. fastapi_app_builder-0.1.0b2/src/fastapi_app_builder/container.py +565 -0
  7. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/exceptions.py +4 -1
  8. fastapi_app_builder-0.1.0b2/src/fastapi_app_builder/installers/__init__.py +15 -0
  9. fastapi_app_builder-0.1.0b2/src/fastapi_app_builder/installers/database.py +179 -0
  10. fastapi_app_builder-0.1.0b2/src/fastapi_app_builder/middleware.py +49 -0
  11. fastapi_app_builder-0.1.0b2/src/fastapi_app_builder/patch.py +243 -0
  12. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/router.py +4 -77
  13. fastapi_app_builder-0.1.0b2/src/fastapi_app_builder/wrapper.py +115 -0
  14. fastapi_app_builder-0.1.0b1/CHANGELOG.md +0 -52
  15. fastapi_app_builder-0.1.0b1/src/fastapi_app_builder/container.py +0 -379
  16. fastapi_app_builder-0.1.0b1/src/fastapi_app_builder/installers/__init__.py +0 -7
  17. fastapi_app_builder-0.1.0b1/src/fastapi_app_builder/installers/database.py +0 -102
  18. fastapi_app_builder-0.1.0b1/src/fastapi_app_builder/middleware.py +0 -38
  19. fastapi_app_builder-0.1.0b1/src/fastapi_app_builder/patch.py +0 -201
  20. fastapi_app_builder-0.1.0b1/src/fastapi_app_builder/wrapper.py +0 -86
  21. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/.gitignore +0 -0
  22. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/LICENSE +0 -0
  23. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/builder.py +0 -0
  24. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/installers/cors.py +0 -0
  25. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/lifetime.py +0 -0
  26. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/py.typed +0 -0
  27. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/resolver.py +0 -0
  28. {fastapi_app_builder-0.1.0b1 → fastapi_app_builder-0.1.0b2}/src/fastapi_app_builder/validation.py +0 -0
@@ -0,0 +1,115 @@
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.0b2] - 2026-11-29
9
+
10
+ ### Upgrading
11
+ Four behavior changes could affect existing apps:
12
+ - For async endpoints, service constructors and factories now run on the event
13
+ loop. Keep them non-blocking and move network or file I/O into the services'
14
+ methods
15
+ - An abstract base class with no abstract methods is no longer injected
16
+ automatically; register it before the router that uses it is defined
17
+ - Scoped services are disposed in reverse creation order
18
+ - An endpoint with injected services is registered as a thin wrapper around
19
+ your function, so `route.endpoint` is the wrapper and
20
+ `route.endpoint.__wrapped__` is your function
21
+
22
+ ### Fixed
23
+ - Endpoints taking a Pydantic request body, `Request` or `WebSocket` failed with
24
+ 500 errors, because these ABC subclasses were mistaken for service interfaces.
25
+ Abstract classes now count as interfaces only when they declare abstract methods
26
+ - Startup validation rejected parameters FastAPI handles itself (`UUID`, enums,
27
+ `Request`, `BackgroundTasks`, ...), parameters with an explicit `Depends()`,
28
+ and constructor parameters that have a default
29
+ - Concurrent requests could fail with a false `CircularDependencyError`, and a
30
+ singleton could be created twice, when services were resolved from several
31
+ threads at once
32
+ - Scoped services were disposed before a `StreamingResponse` body or background
33
+ tasks had finished using them
34
+ - Async `dispose` functions (such as `AsyncSession.close`) were called but never
35
+ awaited, so async sessions were never closed and leaked their connections
36
+ - `install_database()` and `install_database_with_engine()` registered sessions
37
+ without closing them, so each request held its connection until garbage
38
+ collection
39
+
40
+ ### Added
41
+ - `install_async_database()` and `install_async_database_with_engine()`: a
42
+ scoped SQLAlchemy `AsyncSession` per request, closed when the request ends
43
+ - `Services.adispose_scope()`, which awaits async dispose functions. The
44
+ middleware uses it and shields that cleanup from cancellation, so a client
45
+ disconnect or timeout can't leave a session open
46
+ - `install_database_with_engine` is now exported from
47
+ `fastapi_app_builder.installers`
48
+ - `benchmarks/compare_depends.py`, which compares fastapi-app-builder with
49
+ wiring the same services through FastAPI's `Depends()`
50
+
51
+ ### Changed
52
+ - Request handling is about 7x faster. In the included benchmark, a request
53
+ using a layered service graph went from 541 µs to 75 µs, and throughput from
54
+ about 2,700 to 12,100 requests per second. That is now faster than wiring the
55
+ same services with FastAPI's `Depends()` (see the README's Performance
56
+ section):
57
+ - Endpoint services are resolved directly by a thin wrapper, instead of
58
+ going through one FastAPI `Depends()` per parameter
59
+ - `RequestScopeMiddleware` is now a plain ASGI middleware instead of
60
+ `BaseHTTPMiddleware`
61
+ - Services injected into your own `Depends()` functions use `async`
62
+ resolvers, so FastAPI no longer runs each one in its threadpool
63
+ - Constructor type hints are read once per class instead of on every instance
64
+ - Requests skip the disposal scan when no service has a `dispose` function
65
+ - `ServiceNotRegisteredError` messages now say how to register the service
66
+ - WebSocket connections now get a service scope, so scoped services work in
67
+ WebSocket endpoints
68
+ - Scoped services are disposed in reverse creation order, and errors raised by a
69
+ `dispose` function are logged instead of silently ignored
70
+
71
+ ## [0.1.0b1] - 2026-01-20
72
+
73
+ ### Changed
74
+ - **Breaking:** Renamed package from `fastapi-builder` to `fastapi-app-builder`
75
+ - **Breaking:** Renamed import from `fastapi_builder` to `fastapi_app_builder`
76
+
77
+ ### Added
78
+ - `py.typed` marker for PEP 561 type checking support
79
+
80
+ ### Migration
81
+ ```python
82
+ # Before
83
+ from fastapi_builder import AppBuilder
84
+
85
+ # After
86
+ from fastapi_app_builder import AppBuilder
87
+ ```
88
+
89
+ ## [0.1.0a3] - 2026-01-19
90
+
91
+ ### Fixed
92
+ - Resolved mypy strict mode errors
93
+ - Ruff linting fixes
94
+
95
+ ## [0.1.0a2] - 2026-01-18
96
+
97
+ ### Fixed
98
+ - Pre-release fixes and improvements
99
+
100
+ ## [0.1.0a1] - 2026-01-17
101
+
102
+ ### Added
103
+ - Initial alpha release
104
+ - `AppBuilder` for configuring FastAPI applications
105
+ - `Services` container for dependency injection
106
+ - Service lifetimes: Singleton, Scoped, Transient
107
+ - Factory registration with `add_*_factory()` methods
108
+ - `resolve()` function for service resolution anywhere in code
109
+ - Automatic constructor injection
110
+ - Startup validation for missing dependencies
111
+ - `extend()` method to add DI to existing FastAPI apps
112
+ - CORS installer via `install_cors()`
113
+ - SQLAlchemy integration support
114
+ - `InjectableRouter` (optional, standard `APIRouter` works)
115
+ - Installer pattern for modular service registration
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: fastapi-app-builder
3
- Version: 0.1.0b1
3
+ Version: 0.1.0b2
4
4
  Summary: ASP.NET Core-style dependency injection for FastAPI
5
5
  Project-URL: Homepage, https://github.com/Saurus119/fastapi-builder
6
6
  Project-URL: Documentation, https://github.com/Saurus119/fastapi-builder#readme
@@ -26,12 +26,14 @@ Requires-Dist: fastapi>=0.100.0
26
26
  Provides-Extra: all
27
27
  Requires-Dist: sqlalchemy>=2.0.0; extra == 'all'
28
28
  Provides-Extra: dev
29
+ Requires-Dist: aiosqlite>=0.20.0; extra == 'dev'
29
30
  Requires-Dist: coverage>=7.0.0; extra == 'dev'
30
31
  Requires-Dist: httpx>=0.27.0; extra == 'dev'
31
32
  Requires-Dist: mypy>=1.9.0; extra == 'dev'
32
33
  Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
33
34
  Requires-Dist: pytest>=8.0.0; extra == 'dev'
34
35
  Requires-Dist: ruff>=0.8.0; extra == 'dev'
36
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.0; extra == 'dev'
35
37
  Provides-Extra: sqlalchemy
36
38
  Requires-Dist: sqlalchemy>=2.0.0; extra == 'sqlalchemy'
37
39
  Description-Content-Type: text/markdown
@@ -40,8 +42,8 @@ Description-Content-Type: text/markdown
40
42
 
41
43
  [![PyPI version](https://img.shields.io/pypi/v/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
42
44
  [![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
+ [![Downloads](https://img.shields.io/pypi/dm/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
46
+ [![License](https://img.shields.io/pypi/l/fastapi-app-builder.svg)](https://github.com/Saurus119/fastapi-builder/blob/main/LICENSE)
45
47
 
46
48
  [![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
49
 
@@ -53,6 +55,8 @@ ASP.NET Core-style dependency injection for FastAPI - clean controllers, builder
53
55
  - **Standard FastAPI** - Use standard `APIRouter` - no custom router classes needed
54
56
  - **Builder pattern** - Familiar `AppBuilder` for application configuration
55
57
  - **Proper lifetimes** - Singleton, Scoped (per-request), and Transient
58
+ - **Async-ready** - Async endpoints, WebSockets, and SQLAlchemy `AsyncSession` with automatic cleanup
59
+ - **Fast** - Faster than wiring the same services with FastAPI's `Depends()` ([benchmark](#performance))
56
60
  - **Fail fast** - Validate all dependencies at startup
57
61
  - **Familiar API** - Mirror .NET naming conventions
58
62
 
@@ -67,6 +71,11 @@ With SQLAlchemy support:
67
71
  pip install fastapi-app-builder[sqlalchemy]
68
72
  ```
69
73
 
74
+ With async SQLAlchemy, plus the async driver for your database (e.g. `asyncpg`):
75
+ ```bash
76
+ pip install "fastapi-app-builder[sqlalchemy]" "sqlalchemy[asyncio]" asyncpg
77
+ ```
78
+
70
79
  ## Quick Start
71
80
 
72
81
  ```python
@@ -130,6 +139,8 @@ builder.add_controller(user_router)
130
139
  app = builder.build()
131
140
  ```
132
141
 
142
+ > **Registration order:** a parameter typed with an interface (a `Protocol`, or an abstract class with abstract methods) is injected no matter when its service is registered. A concrete class, such as `UserService` or SQLAlchemy's `Session`, is only injected if it is registered before the router is defined, so register those before importing your controllers.
143
+
133
144
  ## Service Lifetimes
134
145
 
135
146
  ### Singleton
@@ -139,7 +150,7 @@ builder.services.add_singleton(IMyService, MyService)
139
150
  ```
140
151
 
141
152
  ### Scoped
142
- One instance per HTTP request:
153
+ One instance per HTTP request (or per WebSocket connection):
143
154
  ```python
144
155
  builder.services.add_scoped(IMyService, MyService)
145
156
  ```
@@ -158,6 +169,8 @@ builder.services.add_singleton_factory(IMyService, lambda: MyService(config))
158
169
  builder.services.add_scoped_factory(IMyService, create_my_service)
159
170
  ```
160
171
 
172
+ For async endpoints, constructors and factories run on the event loop, so keep them fast and non-blocking. Do I/O such as network calls in your services' (async) methods, not while the service is being created. `async def` factories are not supported.
173
+
161
174
  ## Nested Dependencies
162
175
 
163
176
  Dependencies are automatically resolved via constructor injection:
@@ -261,6 +274,8 @@ builder.services.add_scoped(IUserService, UserService)
261
274
  # builder.build() will raise ValidationError
262
275
  ```
263
276
 
277
+ Validation checks that every service an endpoint or constructor needs is registered, and detects circular dependencies. Parameters FastAPI handles itself, such as `Request`, `BackgroundTasks`, Pydantic request bodies, and path or query parameters like `UUID` or enums, are left to FastAPI.
278
+
264
279
  ## Extending an Existing FastAPI App
265
280
 
266
281
  Use `extend()` to add DI to an existing FastAPI app:
@@ -290,27 +305,86 @@ builder.extend(app) # Adds DI to existing app
290
305
 
291
306
  ## SQLAlchemy Integration
292
307
 
308
+ The built-in installers register a scoped session: one per request, closed when the request ends so its connection goes back to the pool. Install the database before defining routers that take a session, since `Session` and `AsyncSession` are concrete classes (see [registration order](#using-standard-apirouter)).
309
+
310
+ ### Async
311
+
293
312
  ```python
294
- from sqlalchemy import create_engine
295
- from sqlalchemy.orm import Session, sessionmaker
313
+ from fastapi import APIRouter
314
+ from sqlalchemy.ext.asyncio import AsyncSession
296
315
  from fastapi_app_builder import AppBuilder
316
+ from fastapi_app_builder.installers import install_async_database
317
+
318
+ builder = AppBuilder()
319
+ builder.install(install_async_database("postgresql+asyncpg://user:password@localhost/mydb"))
320
+
321
+ router = APIRouter(prefix="/users")
322
+
323
+ @router.get("/{user_id}")
324
+ async def get_user(user_id: int, session: AsyncSession):
325
+ user = await session.get(User, user_id)
326
+ return {"id": user.id, "name": user.name}
327
+ ```
297
328
 
298
- engine = create_engine("sqlite:///./app.db")
299
- SessionLocal = sessionmaker(bind=engine)
329
+ ### Sync
300
330
 
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
- )
331
+ ```python
332
+ from fastapi import APIRouter
333
+ from sqlalchemy.orm import Session
334
+ from fastapi_app_builder import AppBuilder
335
+ from fastapi_app_builder.installers import install_database
308
336
 
309
337
  builder = AppBuilder()
310
- builder.install(install_database)
338
+ builder.install(install_database("sqlite:///./app.db"))
339
+
340
+ router = APIRouter(prefix="/users")
341
+
342
+ @router.get("/{user_id}")
343
+ def get_user(user_id: int, session: Session):
344
+ user = session.get(User, user_id)
345
+ return {"id": user.id, "name": user.name}
346
+ ```
347
+
348
+ To reuse an engine you created yourself (for pool settings or `create_all()`), use `install_database_with_engine(engine)` or `install_async_database_with_engine(engine)`.
349
+
350
+ ### Custom session setup
351
+
352
+ For full control, register the session yourself with a `dispose` function. It can be sync or async, and it runs even if the request fails:
353
+
354
+ ```python
355
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
356
+
357
+ engine = create_async_engine("postgresql+asyncpg://user:password@localhost/mydb")
358
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
359
+
360
+ builder.services.add_scoped_factory(
361
+ AsyncSession,
362
+ factory=SessionLocal,
363
+ dispose=lambda s: s.close(), # Awaited, since AsyncSession.close() is async
364
+ )
311
365
  ```
312
366
 
313
- The `dispose` parameter ensures resources are properly cleaned up when the request ends, even if an exception occurs.
367
+ Scoped services are disposed once the response has been fully sent, including streaming bodies and background tasks, in reverse creation order. Cleanup still completes if the request is cancelled, for example when the client disconnects.
368
+
369
+ ## Performance
370
+
371
+ Injecting services with fastapi-app-builder is faster than wiring the same services with FastAPI's `Depends()`:
372
+
373
+ | Scenario | Hand-wired (no DI) | `Depends()`, `def` providers | `Depends()`, `async def` providers | fastapi-app-builder |
374
+ |---|---:|---:|---:|---:|
375
+ | Layered services | 66 µs | 829 µs | 96 µs | **75 µs** |
376
+ | Layered + DB cleanup | 65 µs | 924 µs | 109 µs | **78 µs** |
377
+ | One service, no dependencies | 63 µs | 212 µs | 69 µs | **68 µs** |
378
+
379
+ Time per request; lower is better. In the layered scenario, the endpoint uses a service and an audit log, which share a repository, which uses a DB context; the service also uses a singleton cache. The cleanup variant closes the DB context after each request, with a `yield` dependency in FastAPI and a `dispose` function here. Requests are sent straight to the ASGI app, so the numbers are framework and DI overhead only, without network or server time. Measured with Python 3.13 and FastAPI 0.128 on Windows 11. Run [`benchmarks/compare_depends.py`](benchmarks/compare_depends.py) to measure on your own machine; the `def` column varies most between runs.
380
+
381
+ Why it's faster:
382
+
383
+ - **No `Depends()` per service.** FastAPI solves every `Depends()` parameter with its dependency machinery, which costs roughly 5–6 µs per parameter per request. fastapi-app-builder hides service parameters from FastAPI and resolves all of them in one plain call before the endpoint runs, and services depend on each other through ordinary constructor calls.
384
+ - **No threadpool hops.** FastAPI runs every plain `def` provider in its threadpool, so the style FastAPI's docs use pays a thread hop per provider on every request. That's why the `def` column is so much slower, and it gets worse under concurrent load. Services are resolved in the same call as the endpoint.
385
+ - **Cleanup without generators.** A `yield` dependency needs its own context manager on every request; a `dispose` function is one call after the response.
386
+
387
+ With a single service and nothing behind it, plain `async def` `Depends()` and fastapi-app-builder cost about the same. The gap grows with every service in the graph.
314
388
 
315
389
  ## API Reference
316
390
 
@@ -342,13 +416,24 @@ The dependency injection container.
342
416
  | `add_scoped(interface, impl)` | Register a scoped service |
343
417
  | `add_transient(interface, impl)` | Register a transient service |
344
418
  | `add_singleton_factory(interface, factory)` | Register singleton with factory |
345
- | `add_scoped_factory(interface, factory, dispose=None)` | Register scoped with factory and optional cleanup |
419
+ | `add_scoped_factory(interface, factory, dispose=None)` | Register scoped with factory and optional cleanup (sync or async) |
346
420
  | `add_transient_factory(interface, factory)` | Register transient with factory |
347
421
  | `install(installer)` | Apply an installer function to register services |
348
422
  | `is_registered(interface)` | Check if a service is registered |
349
423
  | `resolve(interface)` | Manually resolve a service |
350
424
  | `validate()` | Validate all registrations |
351
425
 
426
+ ### Installers
427
+
428
+ Available from `fastapi_app_builder.installers`:
429
+
430
+ | Function | Description |
431
+ |----------|-------------|
432
+ | `install_database(url)` | Scoped SQLAlchemy `Session` per request, closed afterwards |
433
+ | `install_database_with_engine(engine)` | Same, using an existing `Engine` |
434
+ | `install_async_database(url)` | Scoped SQLAlchemy `AsyncSession` per request, closed afterwards |
435
+ | `install_async_database_with_engine(engine)` | Same, using an existing `AsyncEngine` |
436
+
352
437
  ### resolve()
353
438
 
354
439
  Resolve a service from anywhere during a request:
@@ -2,8 +2,8 @@
2
2
 
3
3
  [![PyPI version](https://img.shields.io/pypi/v/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
4
4
  [![Python versions](https://img.shields.io/pypi/pyversions/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
5
- [![Downloads](https://static.pepy.tech/badge/fastapi-app-builder)](https://pepy.tech/project/fastapi-app-builder)
6
- [![License](https://img.shields.io/pypi/l/fastapi-app-builder.svg)](https://github.com/Saurus119/fastapi-app-builder/blob/main/LICENSE)
5
+ [![Downloads](https://img.shields.io/pypi/dm/fastapi-app-builder.svg)](https://pypi.org/project/fastapi-app-builder/)
6
+ [![License](https://img.shields.io/pypi/l/fastapi-app-builder.svg)](https://github.com/Saurus119/fastapi-builder/blob/main/LICENSE)
7
7
 
8
8
  [![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)
9
9
 
@@ -15,6 +15,8 @@ ASP.NET Core-style dependency injection for FastAPI - clean controllers, builder
15
15
  - **Standard FastAPI** - Use standard `APIRouter` - no custom router classes needed
16
16
  - **Builder pattern** - Familiar `AppBuilder` for application configuration
17
17
  - **Proper lifetimes** - Singleton, Scoped (per-request), and Transient
18
+ - **Async-ready** - Async endpoints, WebSockets, and SQLAlchemy `AsyncSession` with automatic cleanup
19
+ - **Fast** - Faster than wiring the same services with FastAPI's `Depends()` ([benchmark](#performance))
18
20
  - **Fail fast** - Validate all dependencies at startup
19
21
  - **Familiar API** - Mirror .NET naming conventions
20
22
 
@@ -29,6 +31,11 @@ With SQLAlchemy support:
29
31
  pip install fastapi-app-builder[sqlalchemy]
30
32
  ```
31
33
 
34
+ With async SQLAlchemy, plus the async driver for your database (e.g. `asyncpg`):
35
+ ```bash
36
+ pip install "fastapi-app-builder[sqlalchemy]" "sqlalchemy[asyncio]" asyncpg
37
+ ```
38
+
32
39
  ## Quick Start
33
40
 
34
41
  ```python
@@ -92,6 +99,8 @@ builder.add_controller(user_router)
92
99
  app = builder.build()
93
100
  ```
94
101
 
102
+ > **Registration order:** a parameter typed with an interface (a `Protocol`, or an abstract class with abstract methods) is injected no matter when its service is registered. A concrete class, such as `UserService` or SQLAlchemy's `Session`, is only injected if it is registered before the router is defined, so register those before importing your controllers.
103
+
95
104
  ## Service Lifetimes
96
105
 
97
106
  ### Singleton
@@ -101,7 +110,7 @@ builder.services.add_singleton(IMyService, MyService)
101
110
  ```
102
111
 
103
112
  ### Scoped
104
- One instance per HTTP request:
113
+ One instance per HTTP request (or per WebSocket connection):
105
114
  ```python
106
115
  builder.services.add_scoped(IMyService, MyService)
107
116
  ```
@@ -120,6 +129,8 @@ builder.services.add_singleton_factory(IMyService, lambda: MyService(config))
120
129
  builder.services.add_scoped_factory(IMyService, create_my_service)
121
130
  ```
122
131
 
132
+ For async endpoints, constructors and factories run on the event loop, so keep them fast and non-blocking. Do I/O such as network calls in your services' (async) methods, not while the service is being created. `async def` factories are not supported.
133
+
123
134
  ## Nested Dependencies
124
135
 
125
136
  Dependencies are automatically resolved via constructor injection:
@@ -223,6 +234,8 @@ builder.services.add_scoped(IUserService, UserService)
223
234
  # builder.build() will raise ValidationError
224
235
  ```
225
236
 
237
+ Validation checks that every service an endpoint or constructor needs is registered, and detects circular dependencies. Parameters FastAPI handles itself, such as `Request`, `BackgroundTasks`, Pydantic request bodies, and path or query parameters like `UUID` or enums, are left to FastAPI.
238
+
226
239
  ## Extending an Existing FastAPI App
227
240
 
228
241
  Use `extend()` to add DI to an existing FastAPI app:
@@ -252,27 +265,86 @@ builder.extend(app) # Adds DI to existing app
252
265
 
253
266
  ## SQLAlchemy Integration
254
267
 
268
+ The built-in installers register a scoped session: one per request, closed when the request ends so its connection goes back to the pool. Install the database before defining routers that take a session, since `Session` and `AsyncSession` are concrete classes (see [registration order](#using-standard-apirouter)).
269
+
270
+ ### Async
271
+
255
272
  ```python
256
- from sqlalchemy import create_engine
257
- from sqlalchemy.orm import Session, sessionmaker
273
+ from fastapi import APIRouter
274
+ from sqlalchemy.ext.asyncio import AsyncSession
258
275
  from fastapi_app_builder import AppBuilder
276
+ from fastapi_app_builder.installers import install_async_database
277
+
278
+ builder = AppBuilder()
279
+ builder.install(install_async_database("postgresql+asyncpg://user:password@localhost/mydb"))
280
+
281
+ router = APIRouter(prefix="/users")
282
+
283
+ @router.get("/{user_id}")
284
+ async def get_user(user_id: int, session: AsyncSession):
285
+ user = await session.get(User, user_id)
286
+ return {"id": user.id, "name": user.name}
287
+ ```
259
288
 
260
- engine = create_engine("sqlite:///./app.db")
261
- SessionLocal = sessionmaker(bind=engine)
289
+ ### Sync
262
290
 
263
- def install_database(builder: AppBuilder) -> None:
264
- # Use dispose to automatically close sessions after each request
265
- builder.services.add_scoped_factory(
266
- Session,
267
- factory=SessionLocal,
268
- dispose=lambda s: s.close()
269
- )
291
+ ```python
292
+ from fastapi import APIRouter
293
+ from sqlalchemy.orm import Session
294
+ from fastapi_app_builder import AppBuilder
295
+ from fastapi_app_builder.installers import install_database
270
296
 
271
297
  builder = AppBuilder()
272
- builder.install(install_database)
298
+ builder.install(install_database("sqlite:///./app.db"))
299
+
300
+ router = APIRouter(prefix="/users")
301
+
302
+ @router.get("/{user_id}")
303
+ def get_user(user_id: int, session: Session):
304
+ user = session.get(User, user_id)
305
+ return {"id": user.id, "name": user.name}
306
+ ```
307
+
308
+ To reuse an engine you created yourself (for pool settings or `create_all()`), use `install_database_with_engine(engine)` or `install_async_database_with_engine(engine)`.
309
+
310
+ ### Custom session setup
311
+
312
+ For full control, register the session yourself with a `dispose` function. It can be sync or async, and it runs even if the request fails:
313
+
314
+ ```python
315
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
316
+
317
+ engine = create_async_engine("postgresql+asyncpg://user:password@localhost/mydb")
318
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
319
+
320
+ builder.services.add_scoped_factory(
321
+ AsyncSession,
322
+ factory=SessionLocal,
323
+ dispose=lambda s: s.close(), # Awaited, since AsyncSession.close() is async
324
+ )
273
325
  ```
274
326
 
275
- The `dispose` parameter ensures resources are properly cleaned up when the request ends, even if an exception occurs.
327
+ Scoped services are disposed once the response has been fully sent, including streaming bodies and background tasks, in reverse creation order. Cleanup still completes if the request is cancelled, for example when the client disconnects.
328
+
329
+ ## Performance
330
+
331
+ Injecting services with fastapi-app-builder is faster than wiring the same services with FastAPI's `Depends()`:
332
+
333
+ | Scenario | Hand-wired (no DI) | `Depends()`, `def` providers | `Depends()`, `async def` providers | fastapi-app-builder |
334
+ |---|---:|---:|---:|---:|
335
+ | Layered services | 66 µs | 829 µs | 96 µs | **75 µs** |
336
+ | Layered + DB cleanup | 65 µs | 924 µs | 109 µs | **78 µs** |
337
+ | One service, no dependencies | 63 µs | 212 µs | 69 µs | **68 µs** |
338
+
339
+ Time per request; lower is better. In the layered scenario, the endpoint uses a service and an audit log, which share a repository, which uses a DB context; the service also uses a singleton cache. The cleanup variant closes the DB context after each request, with a `yield` dependency in FastAPI and a `dispose` function here. Requests are sent straight to the ASGI app, so the numbers are framework and DI overhead only, without network or server time. Measured with Python 3.13 and FastAPI 0.128 on Windows 11. Run [`benchmarks/compare_depends.py`](benchmarks/compare_depends.py) to measure on your own machine; the `def` column varies most between runs.
340
+
341
+ Why it's faster:
342
+
343
+ - **No `Depends()` per service.** FastAPI solves every `Depends()` parameter with its dependency machinery, which costs roughly 5–6 µs per parameter per request. fastapi-app-builder hides service parameters from FastAPI and resolves all of them in one plain call before the endpoint runs, and services depend on each other through ordinary constructor calls.
344
+ - **No threadpool hops.** FastAPI runs every plain `def` provider in its threadpool, so the style FastAPI's docs use pays a thread hop per provider on every request. That's why the `def` column is so much slower, and it gets worse under concurrent load. Services are resolved in the same call as the endpoint.
345
+ - **Cleanup without generators.** A `yield` dependency needs its own context manager on every request; a `dispose` function is one call after the response.
346
+
347
+ With a single service and nothing behind it, plain `async def` `Depends()` and fastapi-app-builder cost about the same. The gap grows with every service in the graph.
276
348
 
277
349
  ## API Reference
278
350
 
@@ -304,13 +376,24 @@ The dependency injection container.
304
376
  | `add_scoped(interface, impl)` | Register a scoped service |
305
377
  | `add_transient(interface, impl)` | Register a transient service |
306
378
  | `add_singleton_factory(interface, factory)` | Register singleton with factory |
307
- | `add_scoped_factory(interface, factory, dispose=None)` | Register scoped with factory and optional cleanup |
379
+ | `add_scoped_factory(interface, factory, dispose=None)` | Register scoped with factory and optional cleanup (sync or async) |
308
380
  | `add_transient_factory(interface, factory)` | Register transient with factory |
309
381
  | `install(installer)` | Apply an installer function to register services |
310
382
  | `is_registered(interface)` | Check if a service is registered |
311
383
  | `resolve(interface)` | Manually resolve a service |
312
384
  | `validate()` | Validate all registrations |
313
385
 
386
+ ### Installers
387
+
388
+ Available from `fastapi_app_builder.installers`:
389
+
390
+ | Function | Description |
391
+ |----------|-------------|
392
+ | `install_database(url)` | Scoped SQLAlchemy `Session` per request, closed afterwards |
393
+ | `install_database_with_engine(engine)` | Same, using an existing `Engine` |
394
+ | `install_async_database(url)` | Scoped SQLAlchemy `AsyncSession` per request, closed afterwards |
395
+ | `install_async_database_with_engine(engine)` | Same, using an existing `AsyncEngine` |
396
+
314
397
  ### resolve()
315
398
 
316
399
  Resolve a service from anywhere during a request:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fastapi-app-builder"
3
- version = "0.1.0b1"
3
+ version = "0.1.0b2"
4
4
  description = "ASP.NET Core-style dependency injection for FastAPI"
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
@@ -43,6 +43,8 @@ dev = [
43
43
  "ruff>=0.8.0",
44
44
  "mypy>=1.9.0",
45
45
  "coverage>=7.0.0",
46
+ "sqlalchemy[asyncio]>=2.0.0",
47
+ "aiosqlite>=0.20.0",
46
48
  ]
47
49
  all = [
48
50
  "sqlalchemy>=2.0.0",
@@ -63,6 +65,7 @@ packages = ["src/fastapi_app_builder"]
63
65
 
64
66
  [tool.hatch.build.targets.sdist]
65
67
  exclude = [
68
+ "benchmarks/",
66
69
  "demo/",
67
70
  "examples/",
68
71
  "tests/",
@@ -62,4 +62,4 @@ __all__ = [
62
62
  "ValidationError",
63
63
  ]
64
64
 
65
- __version__ = "0.1.0b1"
65
+ __version__ = "0.1.0b2"