FastAPI Injector

raw JSON →
0.9.0 verified Fri May 01 auth: no python

Integrates python-injector with FastAPI for dependency injection. Current version: 0.9.0. Supports Python 3.10+. Releases are infrequent; last release 2023.

pip install fastapi-injector
error AttributeError: 'FastAPIInjector' object has no attribute 'attach_injector'
cause Using an older version of fastapi-injector where attach_injector didn't exist, or using wrong method name.
fix
Ensure you have version 0.9.0 and call injector.attach_injector(app) (the method exists on the instance). If you have an older version, upgrade.
error InjectorNotFoundException: No injector found for this request
cause The injector was not attached to the app's middleware. The request_injector context is missing.
fix
Make sure to call injector.attach_injector() on your FastAPIInjector instance after creation and before handling requests.
error TypeError: 'Injected' object is not callable
cause Misusing `Injected` as a decorator or calling it as a function instead of using it as a type hint with default value.
fix
Use Injected as a type annotation for a parameter with a default: param: SomeClass = Injected(SomeClass).
gotcha `request_injector` is a property on the app instance, not a standalone import. It must be accessed via `app.state.injector` or `request_injector` only inside a request context when using `AttachInjector` middleware.
fix Use `from fastapi_injector import request_injector` and then `request_injector.get(SomeClass)` only within a request handler after calling `injector.attach_injector(app)`.
deprecated The `Injected` type hint from fastapi_injector is deprecated in favor of using `Depends` with a provider from injector. The direct use of `Injected` may be removed in future versions.
fix Instead of `param: SomeClass = Injected(SomeClass)`, define a dependency function using `Depends` that gets the value from the injector's container.
breaking In version 0.9.0, the `FastAPIInjector` class no longer automatically attaches the injector to the app's state. You must explicitly call `attach_injector()` method on the `FastAPIInjector` instance after creation.
fix After creating `injector = FastAPIInjector(app, modules=[...])`, call `injector.attach_injector()` before the first request.

Basic FastAPI app with injector module binding and route injection.

from fastapi import FastAPI, APIRouter
from fastapi_injector import FastAPIInjector, Injected, request_injector
from injector import Module, singleton, inject

class MyModule(Module):
    def configure(self, binder):
        binder.bind(str, to='Hello, World!', scope=singleton)

app = FastAPI()
injector = FastAPIInjector(app, modules=[MyModule()])

@router.get('/')
async def root(greeting: str = Injected(str)) -> dict:
    return {'message': greeting}

app.include_router(router)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app)