linkd.ext.fastapi¶
Extension module adding support for using linkd-based dependency injection to 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.
- DEFAULT = 'linkd.contexts.default'¶
The base DI context - ALL other contexts are built with this as the parent.
- REQUEST = 'linkd.contexts.fastapi.request'¶
DI context used during HTTP request handling.
- inject(func: InjectedCallableT) InjectedCallableT[source]¶
Specialized decorator enabling linkd-managed dependency injection for fastapi request handlers.
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.
This parameter 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.Example
import fastapi import linkd app = fastapi.FastAPI() linkd.ext.fastapi.use_di_context_middleware(app) @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)], *, # this parameter will be ignored by fastapi, and injected by linkd instead baz: SomeDependency, ) -> None: ...
- use_di_context_middleware(app: fastapi.FastAPI, manager: 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 app = fastapi.FastAPI() linkd.ext.fastapi.use_di_context_middleware(app)