linkd.ext.fastapi¶
Extension module adding support for using linkd-based dependency injection with FastAPI.
See the examples directory for a full working application using this module.
- final class Contexts[source]¶
Collection of the dependency injection context values linkd.ext.fastapi uses.
- REQUEST = 'linkd.contexts.http.request'¶
DI context used during HTTP request handling.
- ROOT = 'linkd.contexts.root'¶
The root DI context - ALL other contexts are built with this as the parent.
- class RequestContainer(registry: registry_.Registry, *, parent: Container | None = None, tag: Context | None = None)[source]¶
- class RootContainer(registry: registry_.Registry, *, parent: Container | None = None, tag: Context | None = None)[source]¶
- inject(func: InjectedCallableT) InjectedCallableT[source]¶
Specialised decorator enabling linkd-managed dependency injection for fastapi request handlers.
This decorator MUST be placed below the fastapi route decorator if it is being used.
- Parameters:
func – The function to enable DI for.
- Returns:
The function with dependency injection enabled.
Warning
The standard
inject()decorator WILL NOT work for fastapi request handlers and this decorator MUST be used in its place.Warning
Linkd-injected parameters MUST be keyword-only, as this decorator rewrites the function signature to hide those parameters from fastapi, so that you can still use fastapi dependency injection on non-kw-only parameters. See the example for more.
Example
import fastapi import linkd manager = linkd.DependencyInjectionManager() app = fastapi.FastAPI() linkd.ext.fastapi.use_di_context_middleware(app, manager) @app.get(...) @linkd.ext.fastapi.inject async def some_handler( # this parameter will be injected by fastapi - path parameter, query parameter, etc. foo: str # custom fastapi dependencies using 'Depends' are also supported bar: Annotated[dict, Depends(some_dependency)], # '*' IS IMPORTANT - if excluded, fastapi will complain about the remaining parameters *, # this parameter will be ignored by fastapi, and injected by linkd instead baz: SomeDependency, ) -> None: ...
- use_di_context_middleware(app: fastapi.FastAPI, manager: _solver.DependencyInjectionManager) None[source]¶
Adds middleware to the given fastapi application to handle setting up a DI context for each HTTP request.
- Parameters:
app – The fastapi application to add the middleware to.
manager – The dependency injection manager to use when entering the DI context.
- Returns:
Example
import fastapi import linkd manager = linkd.DependencyInjectionManager() app = fastapi.FastAPI() linkd.ext.fastapi.use_di_context_middleware(app, manager)