| 1 |
Dependency Injection |
| 2 |
==================== |
| 3 |
|
| 4 |
Litestar has a simple but powerful dependency injection system that allows for declaring dependencies on all layers of |
| 5 |
the application: |
| 6 |
|
| 7 |
.. code-block:: python |
| 8 |
|
| 9 |
from litestar import Controller, Router, Litestar, get |
| 10 |
from litestar.di import NamedDependency, Provide |
| 11 |
|
| 12 |
|
| 13 |
async def bool_fn() -> bool: ... |
| 14 |
|
| 15 |
|
| 16 |
async def dict_fn() -> dict: ... |
| 17 |
|
| 18 |
|
| 19 |
async def list_fn() -> list: ... |
| 20 |
|
| 21 |
|
| 22 |
async def int_fn() -> int: ... |
| 23 |
|
| 24 |
|
| 25 |
class MyController(Controller): |
| 26 |
path = "/controller" |
| 27 |
# on the controller |
| 28 |
dependencies = {"controller_dependency": Provide(list_fn)} |
| 29 |
|
| 30 |
# on the route handler |
| 31 |
@get(path="/handler", dependencies={"local_dependency": Provide(int_fn)}) |
| 32 |
def my_route_handler( |
| 33 |
self, |
| 34 |
app_dependency: NamedDependency[bool], |
| 35 |
router_dependency: NamedDependency[dict], |
| 36 |
controller_dependency: NamedDependency[list], |
| 37 |
local_dependency: NamedDependency[int], |
| 38 |
) -> None: ... |
| 39 |
|
| 40 |
|
| 41 |
# on the router |
| 42 |
my_router = Router( |
| 43 |
path="/router", |
| 44 |
dependencies={"router_dependency": Provide(dict_fn)}, |
| 45 |
route_handlers=[MyController], |
| 46 |
) |
| 47 |
|
| 48 |
# on the app |
| 49 |
app = Litestar( |
| 50 |
route_handlers=[my_router], dependencies={"app_dependency": Provide(bool_fn)} |
| 51 |
) |
| 52 |
|
| 53 |
The above example illustrates how dependencies are declared on the different layers of the application. |
| 54 |
|
| 55 |
.. note:: |
| 56 |
|
| 57 |
Litestar needs the injected types at runtime which might clash with linter rules' recommendation to use ``TYPE_CHECKING``. |
| 58 |
|
| 59 |
.. seealso:: |
| 60 |
|
| 61 |
:ref:`Signature namespace <signature_namespace>` |
| 62 |
|
| 63 |
Dependencies can be either callables - sync or async functions, methods, or class instances that implement the |
| 64 |
:meth:`object.__call__` method, or classes. These are in turn wrapped inside an instance of the |
| 65 |
:class:`Provide <.di.Provide>` class. |
| 66 |
|
| 67 |
|
| 68 |
.. include:: /admonitions/sync-to-thread-info.rst |
| 69 |
|
| 70 |
|
| 71 |
Pre-requisites and scope |
| 72 |
------------------------ |
| 73 |
|
| 74 |
The pre-requisites for dependency injection are these: |
| 75 |
|
| 76 |
#. dependencies must be callables. |
| 77 |
#. dependencies can receive kwargs and a ``self`` arg but not positional args. |
| 78 |
#. the parameter receiving the dependency must be marked with |
| 79 |
:data:`~litestar.di.NamedDependency`, and its name must match the dependency key. |
| 80 |
#. the dependency must be declared using the ``Provide`` class. |
| 81 |
#. the dependency must be in the *scope* of the handler function. |
| 82 |
|
| 83 |
.. deprecated:: 2.24 |
| 84 |
Previously, a dependency was injected into any parameter whose name matched a |
| 85 |
dependency key in scope, with no marker required. Relying on this name-based |
| 86 |
*inference* now emits a :class:`~.exceptions.LitestarDeprecationWarning` and will |
| 87 |
stop working in Litestar 3.0. Mark the parameter with |
| 88 |
:data:`~litestar.di.NamedDependency` instead (see |
| 89 |
:ref:`usage/dependency-injection:Marking dependencies`). |
| 90 |
|
| 91 |
What is *scope* in this context? Dependencies are **isolated** to the context in which they are declared. Thus, in the |
| 92 |
above example, the ``local_dependency`` can only be accessed within the specific route handler on which it was declared; |
| 93 |
The ``controller_dependency`` is available only for route handlers on that specific controller; And the ``router |
| 94 |
dependency`` is available only to the route handlers registered on that particular router. Only the ``app_dependency`` |
| 95 |
is available to all route handlers. |
| 96 |
|
| 97 |
.. seealso:: |
| 98 |
:doc:`/topics/explicit_declarations` |
| 99 |
|
| 100 |
.. _yield_dependencies: |
| 101 |
|
| 102 |
Dependencies with yield (cleanup step) |
| 103 |
-------------------------------------- |
| 104 |
|
| 105 |
In addition to simple callables, dependencies can also be (async) generator functions, which allows |
| 106 |
to execute an additional cleanup step, such as closing a connection, after the handler function |
| 107 |
has returned. |
| 108 |
|
| 109 |
.. admonition:: Technical details |
| 110 |
:class: info |
| 111 |
|
| 112 |
The cleanup stage is executed **after** the handler function returns, but **before** the |
| 113 |
response is sent (in case of HTTP requests) |
| 114 |
|
| 115 |
|
| 116 |
A basic example |
| 117 |
~~~~~~~~~~~~~~~ |
| 118 |
|
| 119 |
.. literalinclude:: /examples/dependency_injection/dependency_yield_simple.py |
| 120 |
:caption: ``dependencies.py`` |
| 121 |
:language: python |
| 122 |
|
| 123 |
|
| 124 |
If you run the code you'll see that ``CONNECTION`` has been reset after the handler function |
| 125 |
returned: |
| 126 |
|
| 127 |
.. code-block:: python |
| 128 |
|
| 129 |
from litestar.testing import TestClient |
| 130 |
from dependencies import app, CONNECTION |
| 131 |
|
| 132 |
with TestClient(app=app) as client: |
| 133 |
print(client.get("/").json()) # {"open": True} |
| 134 |
print(CONNECTION) # {"open": False} |
| 135 |
|
| 136 |
Handling exceptions |
| 137 |
~~~~~~~~~~~~~~~~~~~ |
| 138 |
|
| 139 |
If an exception occurs within the handler function, it will be raised **within** the |
| 140 |
generator, at the point where it first ``yield`` ed. This makes it possible to adapt behaviour |
| 141 |
of the dependency based on exceptions, for example rolling back a database session on error |
| 142 |
and committing otherwise. |
| 143 |
|
| 144 |
.. literalinclude:: /examples/dependency_injection/dependency_yield_exceptions.py |
| 145 |
:caption: ``dependencies.py`` |
| 146 |
:language: python |
| 147 |
|
| 148 |
|
| 149 |
.. code-block:: python |
| 150 |
|
| 151 |
from litestar.testing import TestClient |
| 152 |
from dependencies import STATE, app |
| 153 |
|
| 154 |
with TestClient(app=app) as client: |
| 155 |
response = client.get("/John") |
| 156 |
print(response.json()) # {"John": "hello"} |
| 157 |
print(STATE) # {"result": "OK", "connection": "closed"} |
| 158 |
|
| 159 |
response = client.get("/Peter") |
| 160 |
print(response.status_code) # 500 |
| 161 |
print(STATE) # {"result": "error", "connection": "closed"} |
| 162 |
|
| 163 |
|
| 164 |
.. admonition:: Best Practice |
| 165 |
:class: tip |
| 166 |
|
| 167 |
You should always wrap ``yield`` in a ``try``/``finally`` block, regardless of |
| 168 |
whether you want to handle exceptions, to ensure that the cleanup code is run even |
| 169 |
when exceptions occurred: |
| 170 |
|
| 171 |
.. code-block:: python |
| 172 |
|
| 173 |
def generator_dependency(): |
| 174 |
try: |
| 175 |
yield |
| 176 |
finally: |
| 177 |
... # cleanup code |
| 178 |
|
| 179 |
|
| 180 |
.. attention:: |
| 181 |
|
| 182 |
Do not re-raise exceptions within the dependency. Exceptions caught within these |
| 183 |
dependencies will still be handled by the regular mechanisms without an explicit |
| 184 |
re-raise |
| 185 |
|
| 186 |
|
| 187 |
.. important:: |
| 188 |
|
| 189 |
Exceptions raised during the cleanup step of a dependency will be re-raised in an |
| 190 |
:exc:`ExceptionGroup` (for Python versions < 3.11, the |
| 191 |
`exceptiongroup <https://github.com/agronholm/exceptiongroup>`_ will be used). This |
| 192 |
happens after all dependencies have been cleaned up, so exceptions raised during |
| 193 |
cleanup of one dependencies do not affect the cleanup of other dependencies. |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
Dependency keyword arguments |
| 198 |
---------------------------- |
| 199 |
|
| 200 |
As stated above dependencies can receive kwargs but no args. The reason for this is that dependencies are parsed using |
| 201 |
the same mechanism that parses route handler functions, and they too - like route handler functions, can have data |
| 202 |
injected into them. |
| 203 |
|
| 204 |
In fact, you can inject the same data that you |
| 205 |
can :ref:`inject into route handlers <usage/routing/handlers:"reserved" keyword arguments>`. |
| 206 |
|
| 207 |
.. code-block:: python |
| 208 |
|
| 209 |
from litestar import Controller, patch |
| 210 |
from litestar.di import NamedDependency, Provide |
| 211 |
from pydantic import BaseModel, UUID4 |
| 212 |
|
| 213 |
|
| 214 |
class User(BaseModel): |
| 215 |
id: UUID4 |
| 216 |
name: str |
| 217 |
|
| 218 |
|
| 219 |
async def retrieve_db_user(user_id: UUID4) -> User: ... |
| 220 |
|
| 221 |
|
| 222 |
class UserController(Controller): |
| 223 |
path = "/user" |
| 224 |
dependencies = {"user": Provide(retrieve_db_user)} |
| 225 |
|
| 226 |
@patch(path="/{user_id:uuid}") |
| 227 |
async def get_user(self, user: NamedDependency[User]) -> User: ... |
| 228 |
|
| 229 |
In the above example we have a ``User`` model that we are persisting into a db. The model is fetched using the helper |
| 230 |
method ``retrieve_db_user`` which receives a ``user_id`` kwarg and retrieves the corresponding ``User`` instance. |
| 231 |
The ``UserController`` class maps the ``retrieve_db_user`` provider to the key ``user`` in its ``dependencies`` dictionary. This |
| 232 |
in turn makes it available as a kwarg in the ``get_user`` method. |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
Dependency overrides |
| 238 |
-------------------- |
| 239 |
|
| 240 |
Because dependencies are declared at each level of the app using a string keyed dictionary, overriding dependencies is |
| 241 |
very simple: |
| 242 |
|
| 243 |
.. code-block:: python |
| 244 |
|
| 245 |
from litestar import Controller, get |
| 246 |
from litestar.di import NamedDependency, Provide |
| 247 |
|
| 248 |
|
| 249 |
def bool_fn() -> bool: ... |
| 250 |
|
| 251 |
|
| 252 |
def dict_fn() -> dict: ... |
| 253 |
|
| 254 |
|
| 255 |
class MyController(Controller): |
| 256 |
path = "/controller" |
| 257 |
# on the controller |
| 258 |
dependencies = {"some_dependency": Provide(dict_fn)} |
| 259 |
|
| 260 |
# on the route handler |
| 261 |
@get(path="/handler", dependencies={"some_dependency": Provide(bool_fn)}) |
| 262 |
def my_route_handler( |
| 263 |
self, |
| 264 |
some_dependency: NamedDependency[bool], |
| 265 |
) -> None: ... |
| 266 |
|
| 267 |
The lower scoped route handler function declares a dependency with the same key as the one declared on the higher scoped |
| 268 |
controller. The lower scoped dependency therefore overrides the higher scoped one. |
| 269 |
|
| 270 |
|
| 271 |
The ``Provide`` class |
| 272 |
---------------------- |
| 273 |
|
| 274 |
The :class:`Provide <.di.Provide>` class is a wrapper used for dependency injection. To inject a callable you must wrap |
| 275 |
it in ``Provide``: |
| 276 |
|
| 277 |
.. code-block:: python |
| 278 |
|
| 279 |
from random import randint |
| 280 |
from litestar import get |
| 281 |
from litestar.di import NamedDependency, Provide |
| 282 |
|
| 283 |
|
| 284 |
def my_dependency() -> int: |
| 285 |
return randint(1, 10) |
| 286 |
|
| 287 |
|
| 288 |
@get( |
| 289 |
"/some-path", |
| 290 |
dependencies={ |
| 291 |
"my_dep": Provide( |
| 292 |
my_dependency, |
| 293 |
) |
| 294 |
}, |
| 295 |
) |
| 296 |
def my_handler(my_dep: NamedDependency[int]) -> None: ... |
| 297 |
|
| 298 |
|
| 299 |
.. attention:: |
| 300 |
|
| 301 |
If :class:`Provide.use_cache <.di.Provide>` is ``True``, the return value of the function will be memoized the first |
| 302 |
time it is called and then will be used. There is no sophisticated comparison of kwargs, LRU implementation, etc., so |
| 303 |
you should be careful when you choose to use this option. Note that dependencies will only be called once per |
| 304 |
request, even with ``Provide.use_cache`` set to ``False``. |
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
Dependencies within dependencies |
| 309 |
-------------------------------- |
| 310 |
|
| 311 |
You can inject dependencies into other dependencies, exactly like you would into handler |
| 312 |
functions: |
| 313 |
|
| 314 |
.. code-block:: python |
| 315 |
|
| 316 |
from litestar import Litestar, get |
| 317 |
from litestar.di import NamedDependency, Provide |
| 318 |
from random import randint |
| 319 |
|
| 320 |
|
| 321 |
async def first_dependency() -> int: |
| 322 |
return randint(1, 10) |
| 323 |
|
| 324 |
|
| 325 |
async def second_dependency(injected_integer: NamedDependency[int]) -> bool: |
| 326 |
return injected_integer % 2 == 0 |
| 327 |
|
| 328 |
|
| 329 |
@get("/true-or-false") |
| 330 |
def true_or_false_handler(injected_bool: NamedDependency[bool]) -> str: |
| 331 |
return "it's true!" if injected_bool else "nope, it's false..." |
| 332 |
|
| 333 |
|
| 334 |
app = Litestar( |
| 335 |
route_handlers=[true_or_false_handler], |
| 336 |
dependencies={ |
| 337 |
"injected_integer": first_dependency, |
| 338 |
"injected_bool": second_dependency, |
| 339 |
}, |
| 340 |
) |
| 341 |
|
| 342 |
.. note:: |
| 343 |
|
| 344 |
The rules for `dependency overrides`_ apply here as well. |
| 345 |
|
| 346 |
|
| 347 |
Marking dependencies |
| 348 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 349 |
|
| 350 |
A parameter that should receive an injected dependency is marked with the |
| 351 |
:data:`~litestar.di.NamedDependency` generic. The parameter name is matched against the |
| 352 |
dependency keys in scope, and the type wrapped by ``NamedDependency`` is used to validate |
| 353 |
the injected value: |
| 354 |
|
| 355 |
.. code-block:: python |
| 356 |
|
| 357 |
from litestar import get |
| 358 |
from litestar.di import NamedDependency, Provide |
| 359 |
|
| 360 |
|
| 361 |
async def my_dependency() -> int: ... |
| 362 |
|
| 363 |
|
| 364 |
@get("/", dependencies={"my_dep": my_dependency}) |
| 365 |
def handler(my_dep: NamedDependency[int]) -> None: ... |
| 366 |
|
| 367 |
.. deprecated:: 2.24 |
| 368 |
Earlier versions *inferred* dependencies: any parameter whose name matched a |
| 369 |
dependency key in scope was injected automatically, without a marker. Relying on |
| 370 |
this now emits a :class:`~.exceptions.LitestarDeprecationWarning` and will stop |
| 371 |
working in Litestar 3.0. |
| 372 |
|
| 373 |
.. code-block:: python |
| 374 |
|
| 375 |
# Deprecated: ``my_dep`` is injected only because its name matches the |
| 376 |
# dependency key. Mark it with ``NamedDependency[int]`` instead. |
| 377 |
@get("/", dependencies={"my_dep": Provide(my_dependency)}) |
| 378 |
def handler(my_dep: int) -> None: ... |
| 379 |
|
| 380 |
|
| 381 |
Exclude dependencies with default values from OpenAPI docs |
| 382 |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 383 |
|
| 384 |
Depending on your application design, it is possible to have a dependency declared in a handler or |
| 385 |
:class:`Provide <.di.Provide>` function that has a default value. If the dependency isn't provided for the route, the |
| 386 |
default should be used by the function. |
| 387 |
|
| 388 |
By declaring the parameter to be a dependency, Litestar knows to exclude it from the docs: |
| 389 |
|
| 390 |
.. literalinclude:: /examples/dependency_injection/dependency_with_dependency_fn_and_default.py |
| 391 |
:caption: Dependency with default value |
| 392 |
:language: python |
| 393 |
|
| 394 |
|
| 395 |
Early detection if a dependency isn't provided |
| 396 |
++++++++++++++++++++++++++++++++++++++++++++++ |
| 397 |
|
| 398 |
The other side of the same coin is when a dependency isn't provided, and no default is |
| 399 |
specified. Without the :data:`~litestar.di.NamedDependency` marker, the parameter is |
| 400 |
treated like any other unmarked handler kwarg, i.e. it raises a |
| 401 |
:class:`~.exceptions.LitestarDeprecationWarning` about a missing explicit parameter |
| 402 |
marker, and the route will then fail at request time because no matching query parameter |
| 403 |
was supplied. |
| 404 |
|
| 405 |
Adding :data:`~litestar.di.NamedDependency` makes the contract explicit and lets |
| 406 |
Litestar fail at application boot rather than at request time: |
| 407 |
|
| 408 |
.. literalinclude:: /examples/dependency_injection/dependency_non_optional_not_provided.py |
| 409 |
:caption: Dependency not provided error |
| 410 |
:language: python |
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
Bypassing validation |
| 415 |
-------------------- |
| 416 |
|
| 417 |
By default, injected dependency values are validated by Litestar, for example, this |
| 418 |
application will raise an internal server error: |
| 419 |
|
| 420 |
.. literalinclude:: /examples/dependency_injection/dependency_validation_error.py |
| 421 |
:caption: Dependency validation error |
| 422 |
:language: python |
| 423 |
|
| 424 |
|
| 425 |
This validation can be bypassed using the :data:`~litestar.params.SkipValidation` marker: |
| 426 |
|
| 427 |
.. literalinclude:: /examples/dependency_injection/dependency_skip_validation.py |
| 428 |
:caption: Bypassing dependency validation |
| 429 |
:language: python |