fastapi-app-builder 0.1.0b1__py3-none-any.whl

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,65 @@
1
+ """FastAPI Builder - ASP.NET Core-style dependency injection for FastAPI.
2
+
3
+ This package provides a clean, familiar dependency injection experience for
4
+ FastAPI applications, inspired by ASP.NET Core's DI system.
5
+
6
+ Features:
7
+ - Clean controllers with no Depends() boilerplate
8
+ - Standard FastAPI APIRouter - no custom router classes needed
9
+ - Builder pattern for application configuration
10
+ - Proper service lifetimes (Singleton, Scoped, Transient)
11
+ - Startup validation to catch missing dependencies
12
+ - Familiar .NET-style naming conventions
13
+
14
+ Example:
15
+ from typing import Protocol
16
+ from fastapi import APIRouter
17
+ from fastapi_app_builder import AppBuilder
18
+
19
+ # Define your services
20
+ class IUserService(Protocol):
21
+ def get_user(self, user_id: int) -> dict: ...
22
+
23
+ class UserService:
24
+ def get_user(self, user_id: int) -> dict:
25
+ return {"id": user_id, "name": "John"}
26
+
27
+ # Create router - can be in a separate file, imported in any order
28
+ router = APIRouter(prefix="/users")
29
+
30
+ @router.get("/{user_id}")
31
+ async def get_user(user_id: int, user_service: IUserService):
32
+ return user_service.get_user(user_id)
33
+
34
+ # Configure and build application
35
+ builder = AppBuilder()
36
+ builder.services.add_scoped(IUserService, UserService)
37
+ builder.add_controller(router)
38
+ app = builder.build()
39
+ """
40
+
41
+ from .builder import AppBuilder
42
+ from .container import Services
43
+ from .exceptions import (
44
+ CircularDependencyError,
45
+ ScopeNotFoundError,
46
+ ServiceNotRegisteredError,
47
+ ValidationError,
48
+ )
49
+ from .lifetime import Lifetime
50
+ from .resolver import resolve
51
+ from .router import InjectableRouter
52
+
53
+ __all__ = [
54
+ "AppBuilder",
55
+ "Services",
56
+ "Lifetime",
57
+ "InjectableRouter",
58
+ "resolve",
59
+ "ServiceNotRegisteredError",
60
+ "CircularDependencyError",
61
+ "ScopeNotFoundError",
62
+ "ValidationError",
63
+ ]
64
+
65
+ __version__ = "0.1.0b1"
@@ -0,0 +1,360 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from typing import TYPE_CHECKING
5
+
6
+ from fastapi import APIRouter, FastAPI
7
+
8
+ from .container import Services
9
+ from .exceptions import ValidationError
10
+ from .middleware import RequestScopeMiddleware
11
+ from .patch import set_global_services
12
+
13
+ if TYPE_CHECKING:
14
+ from .router import InjectableRouter
15
+
16
+
17
+ class AppBuilder:
18
+ """Main entry point for configuring FastAPI application.
19
+
20
+ Provides a builder pattern for configuring dependency injection,
21
+ adding controllers, and building a FastAPI application.
22
+
23
+ IMPORTANT: Register all services BEFORE importing/creating routers
24
+ that depend on those services. This allows the automatic DI to work.
25
+
26
+ Example:
27
+ from fastapi_app_builder import AppBuilder
28
+
29
+ # 1. Create builder and register services FIRST
30
+ builder = AppBuilder()
31
+ builder.services.add_scoped(IUserService, UserService)
32
+
33
+ # 2. Import controllers AFTER services are registered
34
+ from controllers import user_router
35
+
36
+ # 3. Add controllers and build
37
+ builder.add_controller(user_router)
38
+ app = builder.build()
39
+
40
+ With this pattern, you can use standard FastAPI APIRouter:
41
+
42
+ # controllers.py
43
+ from fastapi import APIRouter
44
+
45
+ router = APIRouter(prefix="/users")
46
+
47
+ @router.get("/{user_id}")
48
+ async def get_user(user_id: int, user_service: IUserService):
49
+ return user_service.get_user(user_id)
50
+ """
51
+
52
+ def __init__(self) -> None:
53
+ self._services = Services()
54
+ self._controllers: list[APIRouter | InjectableRouter] = []
55
+ self._installers: list[Callable[[AppBuilder], None]] = []
56
+ self._validation_enabled = True
57
+
58
+ # FastAPI configuration
59
+ self._title = "FastAPI"
60
+ self._version = "0.1.0"
61
+ self._description = ""
62
+ self._docs_url: str | None = "/docs"
63
+ self._redoc_url: str | None = "/redoc"
64
+ self._openapi_url: str | None = "/openapi.json"
65
+
66
+ # CORS configuration
67
+ self._cors_config: dict[str, object] | None = None
68
+
69
+ # Set this as the global services container for automatic DI
70
+ set_global_services(self._services)
71
+
72
+ @property
73
+ def services(self) -> Services:
74
+ """Access the dependency injection container."""
75
+ return self._services
76
+
77
+ # Controller registration
78
+ def add_controller(
79
+ self, router: APIRouter | InjectableRouter
80
+ ) -> AppBuilder:
81
+ """Add a controller (router) to the application.
82
+
83
+ Supports both standard FastAPI APIRouter and InjectableRouter.
84
+
85
+ Args:
86
+ router: FastAPI APIRouter or InjectableRouter instance
87
+
88
+ Returns:
89
+ Self for method chaining
90
+ """
91
+ self._controllers.append(router)
92
+ return self
93
+
94
+ # Installer pattern
95
+ def install(
96
+ self,
97
+ installer: Callable[[AppBuilder], None],
98
+ ) -> AppBuilder:
99
+ """Apply an installer function to configure the builder.
100
+
101
+ Installers are functions that take an AppBuilder and configure it.
102
+ This allows for modular configuration of services.
103
+
104
+ Args:
105
+ installer: Function that configures the builder
106
+
107
+ Returns:
108
+ Self for method chaining
109
+
110
+ Example:
111
+ def install_repositories(builder: AppBuilder) -> None:
112
+ builder.services.add_scoped(IUserRepository, UserRepository)
113
+
114
+ builder.install(install_repositories)
115
+ """
116
+ installer(self)
117
+ return self
118
+
119
+ # Configuration methods
120
+ def with_validation(self, enabled: bool) -> AppBuilder:
121
+ """Enable or disable startup validation.
122
+
123
+ When enabled, all service registrations are validated at build time.
124
+
125
+ Args:
126
+ enabled: Whether to validate at startup
127
+
128
+ Returns:
129
+ Self for method chaining
130
+ """
131
+ self._validation_enabled = enabled
132
+ return self
133
+
134
+ def with_title(self, title: str) -> AppBuilder:
135
+ """Set the application title.
136
+
137
+ Args:
138
+ title: Application title for OpenAPI docs
139
+
140
+ Returns:
141
+ Self for method chaining
142
+ """
143
+ self._title = title
144
+ return self
145
+
146
+ def with_version(self, version: str) -> AppBuilder:
147
+ """Set the application version.
148
+
149
+ Args:
150
+ version: Application version for OpenAPI docs
151
+
152
+ Returns:
153
+ Self for method chaining
154
+ """
155
+ self._version = version
156
+ return self
157
+
158
+ def with_description(self, description: str) -> AppBuilder:
159
+ """Set the application description.
160
+
161
+ Args:
162
+ description: Application description for OpenAPI docs
163
+
164
+ Returns:
165
+ Self for method chaining
166
+ """
167
+ self._description = description
168
+ return self
169
+
170
+ def with_docs_url(self, url: str | None) -> AppBuilder:
171
+ """Set the Swagger UI docs URL.
172
+
173
+ Args:
174
+ url: URL path for Swagger docs, or None to disable
175
+
176
+ Returns:
177
+ Self for method chaining
178
+ """
179
+ self._docs_url = url
180
+ return self
181
+
182
+ def with_redoc_url(self, url: str | None) -> AppBuilder:
183
+ """Set the ReDoc URL.
184
+
185
+ Args:
186
+ url: URL path for ReDoc, or None to disable
187
+
188
+ Returns:
189
+ Self for method chaining
190
+ """
191
+ self._redoc_url = url
192
+ return self
193
+
194
+ def with_openapi_url(self, url: str | None) -> AppBuilder:
195
+ """Set the OpenAPI schema URL.
196
+
197
+ Args:
198
+ url: URL path for OpenAPI schema, or None to disable
199
+
200
+ Returns:
201
+ Self for method chaining
202
+ """
203
+ self._openapi_url = url
204
+ return self
205
+
206
+ # Built-in installers
207
+ def install_cors(
208
+ self,
209
+ origins: list[str],
210
+ allow_credentials: bool = True,
211
+ allow_methods: list[str] | None = None,
212
+ allow_headers: list[str] | None = None,
213
+ ) -> AppBuilder:
214
+ """Configure CORS middleware.
215
+
216
+ Args:
217
+ origins: List of allowed origins
218
+ allow_credentials: Whether to allow credentials
219
+ allow_methods: List of allowed HTTP methods (default: all)
220
+ allow_headers: List of allowed headers (default: all)
221
+
222
+ Returns:
223
+ Self for method chaining
224
+ """
225
+ self._cors_config = {
226
+ "allow_origins": origins,
227
+ "allow_credentials": allow_credentials,
228
+ "allow_methods": allow_methods or ["*"],
229
+ "allow_headers": allow_headers or ["*"],
230
+ }
231
+ return self
232
+
233
+ # Build
234
+ def build(self) -> FastAPI:
235
+ """Build and return a new FastAPI application.
236
+
237
+ This method:
238
+ 1. Validates all service registrations (if enabled)
239
+ 2. Creates the FastAPI application with configured settings
240
+ 3. Adds middleware for request-scoped services
241
+ 4. Includes all controllers
242
+
243
+ Returns:
244
+ Configured FastAPI application
245
+
246
+ Raises:
247
+ ValidationError: If validation is enabled and fails
248
+ """
249
+ # Validate registrations
250
+ if self._validation_enabled:
251
+ errors = self._validate()
252
+ if errors:
253
+ raise ValidationError(errors)
254
+
255
+ # Create FastAPI app
256
+ app = FastAPI(
257
+ title=self._title,
258
+ version=self._version,
259
+ description=self._description,
260
+ docs_url=self._docs_url,
261
+ redoc_url=self._redoc_url,
262
+ openapi_url=self._openapi_url,
263
+ )
264
+
265
+ # Add CORS middleware if configured
266
+ if self._cors_config:
267
+ from starlette.middleware.cors import CORSMiddleware
268
+
269
+ app.add_middleware(CORSMiddleware, **self._cors_config) # type: ignore[arg-type]
270
+
271
+ # Apply DI to the app
272
+ self._apply_di(app)
273
+
274
+ return app
275
+
276
+ def extend(self, app: FastAPI) -> FastAPI:
277
+ """Extend an existing FastAPI application with dependency injection.
278
+
279
+ Use this when you have an existing FastAPI app and want to add
280
+ DI support without replacing it. The app's existing configuration
281
+ (title, version, lifespan, routes, etc.) is preserved.
282
+
283
+ Args:
284
+ app: Existing FastAPI instance to extend
285
+
286
+ Returns:
287
+ The same FastAPI instance with DI middleware and controllers added
288
+
289
+ Raises:
290
+ ValidationError: If validation is enabled and fails
291
+
292
+ Example:
293
+ # Create your own FastAPI instance
294
+ app = FastAPI(title="My API", lifespan=my_lifespan)
295
+
296
+ @app.get("/health")
297
+ async def health():
298
+ return {"status": "ok"}
299
+
300
+ # Use builder for DI only
301
+ builder = AppBuilder()
302
+ builder.services.add_scoped(IUserService, UserService)
303
+ builder.add_controller(user_router)
304
+ builder.extend(app) # Adds DI to existing app
305
+ """
306
+ # Validate registrations
307
+ if self._validation_enabled:
308
+ errors = self._validate()
309
+ if errors:
310
+ raise ValidationError(errors)
311
+
312
+ # Apply DI to the app
313
+ self._apply_di(app)
314
+
315
+ return app
316
+
317
+ def _apply_di(self, app: FastAPI) -> None:
318
+ """Apply dependency injection middleware and controllers to an app."""
319
+ # Import here to avoid circular imports
320
+ from .router import InjectableRouter
321
+
322
+ # Add request scope middleware
323
+ app.add_middleware(RequestScopeMiddleware, services=self._services)
324
+
325
+ # Include controllers
326
+ for controller in self._controllers:
327
+ if isinstance(controller, InjectableRouter):
328
+ # InjectableRouter - build with DI support
329
+ router = controller.build_router(self._services)
330
+ app.include_router(router)
331
+ else:
332
+ # Standard APIRouter - the patch handles DI automatically
333
+ app.include_router(controller)
334
+
335
+ def _validate(self) -> list[str]:
336
+ """Validate all registrations and endpoints."""
337
+ from .router import InjectableRouter
338
+
339
+ errors: list[str] = []
340
+
341
+ # Validate service dependencies
342
+ errors.extend(self._services.validate())
343
+
344
+ # Validate endpoint dependencies
345
+ for controller in self._controllers:
346
+ if isinstance(controller, InjectableRouter):
347
+ # Validate InjectableRouter endpoints
348
+ for pending_route in controller.routes:
349
+ errors.extend(
350
+ self._services.validate_endpoint(pending_route.endpoint)
351
+ )
352
+ else:
353
+ # Validate standard APIRouter endpoints
354
+ for base_route in controller.routes:
355
+ if hasattr(base_route, "endpoint"):
356
+ errors.extend(
357
+ self._services.validate_endpoint(base_route.endpoint)
358
+ )
359
+
360
+ return errors