| 1 |
Route handlers |
| 2 |
============== |
| 3 |
|
| 4 |
Route handlers are the core of Litestar. They are constructed by decorating a function or class method with one of the |
| 5 |
handler :term:`decorators <decorator>` exported from Litestar. |
| 6 |
|
| 7 |
For example: |
| 8 |
|
| 9 |
.. code-block:: python |
| 10 |
:caption: Defining a route handler by decorating a function with the :class:`@get() <.handlers.get>` :term:`decorator` |
| 11 |
|
| 12 |
from litestar import get |
| 13 |
|
| 14 |
|
| 15 |
@get("/") |
| 16 |
def greet() -> str: |
| 17 |
return "hello world" |
| 18 |
|
| 19 |
In the above example, the :term:`decorator` includes all the information required to define the endpoint operation for |
| 20 |
the combination of the path ``"/"`` and the HTTP verb ``GET``. In this case it will be a HTTP response with a |
| 21 |
``Content-Type`` header of ``text/plain``. |
| 22 |
|
| 23 |
.. include:: /admonitions/sync-to-thread-info.rst |
| 24 |
|
| 25 |
Declaring paths |
| 26 |
--------------- |
| 27 |
|
| 28 |
All route handler :term:`decorators <decorator>` accept an optional path :term:`argument`. |
| 29 |
This :term:`argument` can be declared as a :term:`kwarg <argument>` using the |
| 30 |
:paramref:`~.handlers.base.BaseRouteHandler.path` parameter: |
| 31 |
|
| 32 |
.. code-block:: python |
| 33 |
:caption: Defining a route handler by passing the path as a keyword argument |
| 34 |
|
| 35 |
from litestar import get |
| 36 |
|
| 37 |
|
| 38 |
@get(path="/some-path") |
| 39 |
async def my_route_handler() -> None: ... |
| 40 |
|
| 41 |
It can also be passed as an :term:`argument` without the keyword: |
| 42 |
|
| 43 |
.. code-block:: python |
| 44 |
:caption: Defining a route handler but not using the keyword argument |
| 45 |
|
| 46 |
from litestar import get |
| 47 |
|
| 48 |
|
| 49 |
@get("/some-path") |
| 50 |
async def my_route_handler() -> None: ... |
| 51 |
|
| 52 |
And the value for this :term:`argument` can be either a string path, as in the above examples, or a :class:`list` of |
| 53 |
:class:`string <str>` paths: |
| 54 |
|
| 55 |
.. code-block:: python |
| 56 |
:caption: Defining a route handler with multiple paths |
| 57 |
|
| 58 |
from litestar import get |
| 59 |
|
| 60 |
|
| 61 |
@get(["/some-path", "/some-other-path"]) |
| 62 |
async def my_route_handler() -> None: ... |
| 63 |
|
| 64 |
This is particularly useful when you want to have optional |
| 65 |
:ref:`path parameters <usage/routing/parameters:Path Parameters>`: |
| 66 |
|
| 67 |
.. code-block:: python |
| 68 |
:caption: Defining a route handler with a path that has an optional path parameter |
| 69 |
|
| 70 |
from litestar import get |
| 71 |
from litestar.params import FromPath |
| 72 |
|
| 73 |
@get( |
| 74 |
["/some-path", "/some-path/{some_id:int}"], |
| 75 |
) |
| 76 |
async def my_route_handler(some_id: FromPath[int] = 1) -> None: ... |
| 77 |
|
| 78 |
.. _handler-function-kwargs: |
| 79 |
|
| 80 |
"reserved" keyword arguments |
| 81 |
---------------------------- |
| 82 |
|
| 83 |
Route handler functions or methods access various data by declaring these as annotated function :term:`kwargs <argument>`. The annotated |
| 84 |
:term:`kwargs <argument>` are inspected by Litestar and then injected into the request handler. |
| 85 |
|
| 86 |
The following sources can be accessed using annotated function :term:`kwargs <argument>`: |
| 87 |
|
| 88 |
- :ref:`path, query, header, and cookie parameters <parameter-types>`, declared with |
| 89 |
:data:`~.params.FromPath`, :data:`~.params.FromQuery`, :data:`~.params.FromHeader`, |
| 90 |
and :data:`~.params.FromCookie` |
| 91 |
- :doc:`requests </usage/requests>` |
| 92 |
- :doc:`injected dependencies </usage/dependency-injection>` |
| 93 |
|
| 94 |
Additionally, you can specify the following special :term:`kwargs <argument>`, |
| 95 |
(known as "reserved keywords arguments"): |
| 96 |
|
| 97 |
* ``cookies``: injects the request :class:`cookies <.datastructures.cookie.Cookie>` as a parsed |
| 98 |
:class:`dictionary <dict>`. |
| 99 |
* ``headers``: injects the request headers as a parsed :class:`dictionary <dict>`. |
| 100 |
* ``query`` : injects the request ``query_params`` as a parsed :class:`dictionary <dict>`. |
| 101 |
* ``request``: injects the :class:`Request <.connection.Request>` instance. Available only for `HTTP route handlers`_ |
| 102 |
* ``scope`` : injects the ASGI scope :class:`dictionary <dict>`. |
| 103 |
* ``socket``: injects the :class:`WebSocket <.connection.WebSocket>` instance. Available only for `websocket route handlers`_ |
| 104 |
* ``state`` : injects a copy of the application :class:`State <.datastructures.state.State>`. |
| 105 |
* ``body`` : the raw request body. Available only for `HTTP route handlers`_ |
| 106 |
|
| 107 |
.. tip:: |
| 108 |
Note that if your parameters collide with any of the reserved |
| 109 |
:term:`keyword arguments <argument>` above, you can |
| 110 |
:ref:`provide an alternative name <usage/routing/parameters:Aliasing>`. |
| 111 |
|
| 112 |
For example: |
| 113 |
|
| 114 |
.. code-block:: python |
| 115 |
:caption: Providing an alternative name for a reserved keyword argument |
| 116 |
|
| 117 |
from typing import Any, Dict |
| 118 |
from litestar import Request, get |
| 119 |
from litestar.datastructures import Headers, State |
| 120 |
|
| 121 |
|
| 122 |
@get(path="/") |
| 123 |
async def my_request_handler( |
| 124 |
state: State, |
| 125 |
request: Request, |
| 126 |
headers: Dict[str, str], |
| 127 |
query: Dict[str, Any], |
| 128 |
cookies: Dict[str, Any], |
| 129 |
) -> None: ... |
| 130 |
|
| 131 |
.. tip:: You can define a custom typing for your application state and then use it as a type instead of just using the |
| 132 |
:class:`~.datastructures.state.State` class from Litestar |
| 133 |
|
| 134 |
Type annotations |
| 135 |
---------------- |
| 136 |
|
| 137 |
Litestar enforces strict :term:`type annotations <annotation>`. |
| 138 |
Functions decorated by a route handler **must** have all their :term:`arguments <argument>` and return |
| 139 |
value type annotated. |
| 140 |
|
| 141 |
If a type annotation is missing, an :exc:`~.exceptions.ImproperlyConfiguredException` will be raised during the |
| 142 |
application boot-up process. |
| 143 |
|
| 144 |
There are several reasons for why this limitation is enforced: |
| 145 |
|
| 146 |
#. To ensure best practices |
| 147 |
#. To ensure consistent OpenAPI schema generation |
| 148 |
#. To allow Litestar to compute the :term:`arguments <argument>` required by a function during application bootstrap |
| 149 |
|
| 150 |
HTTP route handlers |
| 151 |
------------------- |
| 152 |
|
| 153 |
The most commonly used route handlers are those that handle HTTP requests and responses. |
| 154 |
These route handlers all inherit from the :class:`~.handlers.HTTPRouteHandler` class, which is aliased as the |
| 155 |
:term:`decorator` called :func:`~.handlers.route`: |
| 156 |
|
| 157 |
.. code-block:: python |
| 158 |
:caption: Defining a route handler by decorating a function with the :class:`@route() <.handlers.route>` |
| 159 |
:term:`decorator` |
| 160 |
|
| 161 |
from litestar import HttpMethod, route |
| 162 |
|
| 163 |
|
| 164 |
@route(path="/some-path", http_method=[HttpMethod.GET, HttpMethod.POST]) |
| 165 |
async def my_endpoint() -> None: ... |
| 166 |
|
| 167 |
As mentioned above, :func:`@route() <.handlers.route>` is merely an alias for ``HTTPRouteHandler``, |
| 168 |
thus the below code is equivalent to the one above: |
| 169 |
|
| 170 |
.. code-block:: python |
| 171 |
:caption: Defining a route handler by decorating a function with the |
| 172 |
:class:`HTTPRouteHandler <.handlers.HTTPRouteHandler>` class |
| 173 |
|
| 174 |
from litestar import HttpMethod |
| 175 |
from litestar.handlers.http_handlers import HTTPRouteHandler |
| 176 |
|
| 177 |
|
| 178 |
@HTTPRouteHandler(path="/some-path", http_method=[HttpMethod.GET, HttpMethod.POST]) |
| 179 |
async def my_endpoint() -> None: ... |
| 180 |
|
| 181 |
|
| 182 |
Semantic handler :term:`decorators <decorator>` |
| 183 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 184 |
|
| 185 |
Litestar also includes "semantic" :term:`decorators <decorator>`, that is, :term:`decorators <decorator>` the pre-set |
| 186 |
the :paramref:`~litestar.handlers.HTTPRouteHandler.http_method` :term:`kwarg <argument>` to a specific HTTP verb, |
| 187 |
which correlates with their name: |
| 188 |
|
| 189 |
* :func:`@delete() <.handlers.delete>` |
| 190 |
* :func:`@get() <.handlers.get>` |
| 191 |
* :func:`@head() <.handlers.head>` |
| 192 |
* :func:`@patch() <.handlers.patch>` |
| 193 |
* :func:`@post() <.handlers.post>` |
| 194 |
* :func:`@put() <.handlers.put>` |
| 195 |
|
| 196 |
These are used exactly like :func:`@route() <.handlers.route>` with the sole exception that you cannot configure the |
| 197 |
:paramref:`~.handlers.HTTPRouteHandler.http_method` :term:`kwarg <argument>`: |
| 198 |
|
| 199 |
.. dropdown:: Click to see the predefined route handlers |
| 200 |
|
| 201 |
.. code-block:: python |
| 202 |
:caption: Predefined :term:`decorators <decorator>` for HTTP route handlers |
| 203 |
|
| 204 |
from litestar import delete, get, patch, post, put, head |
| 205 |
from litestar.dto import DTOConfig, DTOData |
| 206 |
from litestar.params import FromPath |
| 207 |
from litestar.plugins.pydantic import PydanticDTO |
| 208 |
|
| 209 |
from pydantic import BaseModel |
| 210 |
|
| 211 |
|
| 212 |
class Resource(BaseModel): ... |
| 213 |
|
| 214 |
|
| 215 |
class PartialResourceDTO(PydanticDTO[Resource]): |
| 216 |
config = DTOConfig(partial=True) |
| 217 |
|
| 218 |
|
| 219 |
@get(path="/resources") |
| 220 |
async def list_resources() -> list[Resource]: ... |
| 221 |
|
| 222 |
|
| 223 |
@post(path="/resources") |
| 224 |
async def create_resource(data: Resource) -> Resource: ... |
| 225 |
|
| 226 |
|
| 227 |
@get(path="/resources/{pk:int}") |
| 228 |
async def retrieve_resource(pk: FromPath[int]) -> Resource: ... |
| 229 |
|
| 230 |
|
| 231 |
@head(path="/resources/{pk:int}") |
| 232 |
async def retrieve_resource_head(pk: FromPath[int]) -> None: ... |
| 233 |
|
| 234 |
|
| 235 |
@put(path="/resources/{pk:int}") |
| 236 |
async def update_resource(data: Resource, pk: FromPath[int]) -> Resource: ... |
| 237 |
|
| 238 |
|
| 239 |
@patch(path="/resources/{pk:int}", dto=PartialResourceDTO) |
| 240 |
async def partially_update_resource( |
| 241 |
data: DTOData[PartialResourceDTO], pk: FromPath[int] |
| 242 |
) -> Resource: ... |
| 243 |
|
| 244 |
|
| 245 |
@delete(path="/resources/{pk:int}") |
| 246 |
async def delete_resource(pk: FromPath[int]) -> None: ... |
| 247 |
|
| 248 |
Although these :term:`decorators <decorator>` are merely subclasses of :class:`~.handlers.HTTPRouteHandler` that pre-set |
| 249 |
the :paramref:`~.handlers.HTTPRouteHandler.http_method`, using :func:`@get() <.handlers.get>`, |
| 250 |
:func:`@patch() <.handlers.patch>`, :func:`@put() <.handlers.put>`, :func:`@delete() <.handlers.delete>`, or |
| 251 |
:func:`@post() <.handlers.post>` instead of :func:`@route() <.handlers.route>` makes the code clearer and simpler. |
| 252 |
|
| 253 |
Furthermore, in the OpenAPI specification each unique combination of HTTP verb (e.g. ``GET``, ``POST``, etc.) and path |
| 254 |
is regarded as a distinct `operation <https://spec.openapis.org/oas/latest.html#operation-object>`_\ , and each |
| 255 |
operation should be distinguished by a unique :paramref:`~.handlers.HTTPRouteHandler.operation_id` and optimally |
| 256 |
also have a :paramref:`~.handlers.HTTPRouteHandler.summary` and |
| 257 |
:paramref:`~.handlers.HTTPRouteHandler.description` sections. |
| 258 |
|
| 259 |
As such, using the :func:`@route() <.handlers.route>` :term:`decorator` is discouraged. |
| 260 |
Instead, the preferred pattern is to share code using secondary class methods or by abstracting code to reusable |
| 261 |
functions. |
| 262 |
|
| 263 |
Websocket route handlers |
| 264 |
------------------------ |
| 265 |
|
| 266 |
A WebSocket connection can be handled with a :func:`@websocket() <.handlers.WebsocketRouteHandler>` route handler. |
| 267 |
|
| 268 |
.. note:: The websocket handler is a low level approach, requiring to handle the socket directly, |
| 269 |
and dealing with keeping it open, exceptions, client disconnects, and content negotiation. |
| 270 |
|
| 271 |
For a more high level approach to handling WebSockets, see :doc:`/usage/websockets` |
| 272 |
|
| 273 |
.. code-block:: python |
| 274 |
:caption: Using the :func:`@websocket() <.handlers.WebsocketRouteHandler>` route handler :term:`decorator` |
| 275 |
|
| 276 |
from litestar import WebSocket, websocket |
| 277 |
|
| 278 |
|
| 279 |
@websocket(path="/socket") |
| 280 |
async def my_websocket_handler(socket: WebSocket) -> None: |
| 281 |
await socket.accept() |
| 282 |
await socket.send_json({...}) |
| 283 |
await socket.close() |
| 284 |
|
| 285 |
The :func:`@websocket() <.handlers.WebsocketRouteHandler>` :term:`decorator` is an alias of the |
| 286 |
:class:`~.handlers.WebsocketRouteHandler` class. Thus, the below code is equivalent to the one above: |
| 287 |
|
| 288 |
.. code-block:: python |
| 289 |
:caption: Using the :class:`~.handlers.WebsocketRouteHandler` class directly |
| 290 |
|
| 291 |
from litestar import WebSocket |
| 292 |
from litestar.handlers.websocket_handlers import WebsocketRouteHandler |
| 293 |
|
| 294 |
|
| 295 |
@WebsocketRouteHandler(path="/socket") |
| 296 |
async def my_websocket_handler(socket: WebSocket) -> None: |
| 297 |
await socket.accept() |
| 298 |
await socket.send_json({...}) |
| 299 |
await socket.close() |
| 300 |
|
| 301 |
In difference to HTTP routes handlers, websocket handlers have the following requirements: |
| 302 |
|
| 303 |
#. They **must** declare a ``socket`` :term:`kwarg <argument>`. |
| 304 |
#. They **must** have a return :term:`annotation` of ``None``. |
| 305 |
#. They **must** be :ref:`async functions <python:async def>`. |
| 306 |
|
| 307 |
These requirements are enforced using inspection, and if any of them is unfulfilled an informative exception |
| 308 |
will be raised. |
| 309 |
|
| 310 |
OpenAPI currently does not support websockets. As such no schema will be generated for these route handlers. |
| 311 |
|
| 312 |
.. seealso:: * :class:`~.handlers.WebsocketRouteHandler` |
| 313 |
* :doc:`/usage/websockets` |
| 314 |
|
| 315 |
ASGI route handlers |
| 316 |
------------------- |
| 317 |
|
| 318 |
If you need to write your own ASGI application, you can do so using the :func:`@asgi() <.handlers.asgi>` :term:`decorator`: |
| 319 |
|
| 320 |
.. code-block:: python |
| 321 |
:caption: Using the :func:`@asgi() <.handlers.asgi>` route handler :term:`decorator` |
| 322 |
|
| 323 |
from litestar.types import Scope, Receive, Send |
| 324 |
from litestar.status_codes import HTTP_400_BAD_REQUEST |
| 325 |
from litestar import Response, asgi |
| 326 |
|
| 327 |
|
| 328 |
@asgi(path="/my-asgi-app") |
| 329 |
async def my_asgi_app(scope: Scope, receive: Receive, send: Send) -> None: |
| 330 |
if scope["type"] == "http": |
| 331 |
if scope["method"] == "GET": |
| 332 |
response = Response({"hello": "world"}) |
| 333 |
await response(scope=scope, receive=receive, send=send) |
| 334 |
return |
| 335 |
response = Response( |
| 336 |
{"detail": "unsupported request"}, status_code=HTTP_400_BAD_REQUEST |
| 337 |
) |
| 338 |
await response(scope=scope, receive=receive, send=send) |
| 339 |
|
| 340 |
Like other route handlers, the :func:`@asgi() <.handlers.asgi>` :term:`decorator` is an alias of the |
| 341 |
:class:`~.handlers.ASGIRouteHandler` class. Thus, the code below is equivalent to the one above: |
| 342 |
|
| 343 |
.. code-block:: python |
| 344 |
:caption: Using the :class:`~.handlers.ASGIRouteHandler` class directly |
| 345 |
|
| 346 |
from litestar import Response |
| 347 |
from litestar.handlers.asgi_handlers import ASGIRouteHandler |
| 348 |
from litestar.status_codes import HTTP_400_BAD_REQUEST |
| 349 |
from litestar.types import Scope, Receive, Send |
| 350 |
|
| 351 |
|
| 352 |
@ASGIRouteHandler(path="/my-asgi-app") |
| 353 |
async def my_asgi_app(scope: Scope, receive: Receive, send: Send) -> None: |
| 354 |
if scope["type"] == "http": |
| 355 |
if scope["method"] == "GET": |
| 356 |
response = Response({"hello": "world"}) |
| 357 |
await response(scope=scope, receive=receive, send=send) |
| 358 |
return |
| 359 |
response = Response( |
| 360 |
{"detail": "unsupported request"}, status_code=HTTP_400_BAD_REQUEST |
| 361 |
) |
| 362 |
await response(scope=scope, receive=receive, send=send) |
| 363 |
|
| 364 |
Limitations of ASGI route handlers |
| 365 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 366 |
|
| 367 |
In difference to the other route handlers, the :func:`@asgi() <.handlers.asgi>` route handler accepts only three |
| 368 |
:term:`kwargs <argument>` that **must** be defined: |
| 369 |
|
| 370 |
* ``scope``, a mapping of values describing the ASGI connection. It always includes a ``type`` key, with the values being |
| 371 |
either ``http`` or ``websocket``, and a ``path`` key. If the type is ``http``, the scope dictionary will also include |
| 372 |
a ``method`` key with the value being one of ``DELETE``, ``GET``, ``POST``, ``PATCH``, ``PUT``, ``HEAD``. |
| 373 |
* ``receive``, an injected function by which the ASGI application receives messages. |
| 374 |
* ``send``, an injected function by which the ASGI application sends messages. |
| 375 |
|
| 376 |
You can read more about these in the `ASGI specification <https://asgi.readthedocs.io/en/latest/specs/main.html>`_. |
| 377 |
|
| 378 |
Additionally, ASGI route handler functions **must** be :ref:`async functions <python:async def>`. |
| 379 |
This is enforced using inspection, and if the function is not an :ref:`async functions <python:async def>`, |
| 380 |
an informative exception will be raised. |
| 381 |
|
| 382 |
See the :class:`ASGIRouteHandler API reference documentation <.handlers.asgi_handlers.ASGIRouteHandler>` for full |
| 383 |
details on the :func:`@asgi() <.handlers.asgi>` :term:`decorator` and the :term:`kwargs <argument>` it accepts. |
| 384 |
|
| 385 |
Route handler indexing |
| 386 |
---------------------- |
| 387 |
|
| 388 |
You can provide a :paramref:`~.handlers.base.BaseRouteHandler.name` :term:`kwarg <argument>` in all route handler |
| 389 |
:term:`decorators <decorator>`. The value for this :term:`kwarg <argument>` **must be unique**, otherwise |
| 390 |
:exc:`~.exceptions.ImproperlyConfiguredException` exception will be raised. |
| 391 |
|
| 392 |
The default value for :paramref:`~.handlers.base.BaseRouteHandler.name` is the value returned by the handler's |
| 393 |
:meth:`~object.__str__` method, which should be the full dotted path to the handler |
| 394 |
(e.g., ``app.controllers.projects.list`` for the ``list`` function residing in the ``app/controllers/projects.py`` file). |
| 395 |
:paramref:`~.handlers.base.BaseRouteHandler.name` can be used to dynamically retrieve (i.e. during runtime) a mapping |
| 396 |
containing the route handler instance and paths. It can also be used to build a URL path for that handler: |
| 397 |
|
| 398 |
.. code-block:: python |
| 399 |
:caption: Using the :paramref:`~.handlers.base.BaseRouteHandler.name` :term:`kwarg <argument>` to retrieve a route |
| 400 |
handler instance and paths |
| 401 |
|
| 402 |
from litestar import Litestar, Request, get |
| 403 |
from litestar.exceptions import NotFoundException |
| 404 |
from litestar.params import FromPath, FromQuery |
| 405 |
from litestar.response import Redirect |
| 406 |
|
| 407 |
|
| 408 |
@get("/abc", name="one") |
| 409 |
def handler_one() -> None: |
| 410 |
pass |
| 411 |
|
| 412 |
|
| 413 |
@get("/xyz", name="two") |
| 414 |
def handler_two() -> None: |
| 415 |
pass |
| 416 |
|
| 417 |
|
| 418 |
@get("/def/{param:int}", name="three") |
| 419 |
def handler_three(param: FromPath[int]) -> None: |
| 420 |
pass |
| 421 |
|
| 422 |
|
| 423 |
@get("/{handler_name:str}", name="four") |
| 424 |
def handler_four(request: Request, handler_name: FromPath[str]) -> Redirect: |
| 425 |
handler_index = request.app.get_handler_index_by_name(handler_name) |
| 426 |
if not handler_index: |
| 427 |
raise NotFoundException(f"no handler matching the name {handler_name} was found") |
| 428 |
|
| 429 |
# handler_index == { "paths": ["/"], "handler": ..., "qualname": ... } |
| 430 |
# do something with the handler index below, e.g. send a redirect response to the handler, or access |
| 431 |
# handler.opt and some values stored there etc. |
| 432 |
|
| 433 |
return Redirect(path=handler_index[0]) |
| 434 |
|
| 435 |
|
| 436 |
@get("/redirect/{param_value:int}", name="five") |
| 437 |
def handler_five(request: Request, param_value: FromPath[int]) -> Redirect: |
| 438 |
path = request.app.route_reverse("three", param=param_value) |
| 439 |
return Redirect(path=path) |
| 440 |
|
| 441 |
|
| 442 |
app = Litestar(route_handlers=[handler_one, handler_two, handler_three]) |
| 443 |
|
| 444 |
As a convenience, you can also pass the route handler directly to :meth:`~.app.Litestar.route_reverse`: |
| 445 |
|
| 446 |
.. code-block:: python |
| 447 |
:caption: Directly retrieving a route handler's path from a reference to that handler |
| 448 |
|
| 449 |
from litestar import Litestar, get |
| 450 |
|
| 451 |
|
| 452 |
@get("/abc", name="one") |
| 453 |
def handler_one() -> None: |
| 454 |
pass |
| 455 |
|
| 456 |
app = Litestar(route_handlers=[handler]) |
| 457 |
|
| 458 |
app.route_reverse(handler_one) # Returns "/abc" |
| 459 |
|
| 460 |
|
| 461 |
:meth:`~.app.Litestar.route_reverse` will raise :exc:`~.exceptions.NoRouteMatchFoundException` if a route with the |
| 462 |
given name was not found, or if any of the passed path :term:`parameters <parameter>` are missing or do not match the |
| 463 |
types in the respective route declaration. As an exception, :class:`str` is accepted in place of |
| 464 |
:class:`~datetime.datetime`, :class:`~datetime.date`, :class:`~datetime.time`, :class:`~datetime.timedelta`, |
| 465 |
:class:`float`, and :class:`~pathlib.Path` parameters, so you can apply custom formatting and pass the result to |
| 466 |
:meth:`~.app.Litestar.route_reverse`. |
| 467 |
|
| 468 |
If handler has multiple paths attached to it, :meth:`~.app.Litestar.route_reverse` will return the path that consumes |
| 469 |
the highest number of the :term:`keyword arguments <argument>` passed to the function. |
| 470 |
|
| 471 |
.. code-block:: python |
| 472 |
:caption: Using the :meth:`~.app.Litestar.route_reverse` method to build a URL path for a route handler |
| 473 |
|
| 474 |
from litestar import get, Request |
| 475 |
from litestar.params import FromPath |
| 476 |
|
| 477 |
|
| 478 |
@get( |
| 479 |
["/some-path", "/some-path/{id:int}", "/some-path/{id:int}/{val:str}"], |
| 480 |
name="handler_name", |
| 481 |
) |
| 482 |
def handler(id: FromPath[int] = 1, val: FromPath[str] = "default") -> None: ... |
| 483 |
|
| 484 |
|
| 485 |
@get("/path-info") |
| 486 |
def path_info(request: Request) -> str: |
| 487 |
path_optional = request.app.route_reverse("handler_name") |
| 488 |
# /some-path` |
| 489 |
|
| 490 |
path_partial = request.app.route_reverse("handler_name", id=100) |
| 491 |
# /some-path/100 |
| 492 |
|
| 493 |
path_full = request.app.route_reverse("handler_name", id=100, val="value") |
| 494 |
# /some-path/100/value` |
| 495 |
|
| 496 |
return f"{path_optional} {path_partial} {path_full}" |
| 497 |
|
| 498 |
When a handler is associated with multiple routes having identical path :term:`parameters <parameter>` |
| 499 |
(e.g., an indexed handler registered across multiple routers), the output of :meth:`~.app.Litestar.route_reverse` is |
| 500 |
unpredictable. This :term:`callable` will return a formatted path; however, its selection may appear arbitrary. |
| 501 |
Therefore, reversing URLs under these conditions is **strongly** advised against. |
| 502 |
|
| 503 |
If you have access to a :class:`~.connection.Request` instance, you can perform reverse lookups using the |
| 504 |
:meth:`~.connection.ASGIConnection.url_for` method, which is similar to :meth:`~.app.Litestar.route_reverse`, but |
| 505 |
returns an absolute URL. |
| 506 |
|
| 507 |
.. _handler_opts: |
| 508 |
|
| 509 |
Adding arbitrary metadata to handlers |
| 510 |
-------------------------------------- |
| 511 |
|
| 512 |
All route handler :term:`decorators <decorator>` accept a key called ``opt`` which accepts a :term:`dictionary <dict>` |
| 513 |
of arbitrary values, e.g., |
| 514 |
|
| 515 |
.. code-block:: python |
| 516 |
:caption: Adding arbitrary metadata to a route handler through the ``opt`` :term:`kwarg <argument>` |
| 517 |
|
| 518 |
from litestar import get |
| 519 |
|
| 520 |
|
| 521 |
@get("/", opt={"my_key": "some-value"}) |
| 522 |
def handler() -> None: ... |
| 523 |
|
| 524 |
This dictionary can be accessed by a :doc:`route guard </usage/security/guards>`, or by accessing the |
| 525 |
:attr:`~.connection.ASGIConnection.route_handler` property on a :class:`~.connection.request.Request` object, |
| 526 |
or using the :class:`ASGI scope <litestar.types.Scope>` object directly. |
| 527 |
|
| 528 |
Building on ``opt``, you can pass any arbitrary :term:`kwarg <argument>` to the route handler :term:`decorator`, |
| 529 |
and it will be automatically set as a key in the ``opt`` dictionary: |
| 530 |
|
| 531 |
.. code-block:: python |
| 532 |
:caption: Adding arbitrary metadata to a route handler through the ``opt`` :term:`kwarg <argument>` |
| 533 |
|
| 534 |
from litestar import get |
| 535 |
|
| 536 |
|
| 537 |
@get("/", my_key="some-value") |
| 538 |
def handler() -> None: ... |
| 539 |
|
| 540 |
|
| 541 |
assert handler.opt["my_key"] == "some-value" |
| 542 |
|
| 543 |
You can specify the ``opt`` :term:`dictionary <dict>` at all layers of your application. |
| 544 |
On specific route handlers, on a controller, a router, and even on the app instance itself as described in |
| 545 |
:ref:`layered architecture <usage/applications:layered architecture>` |
| 546 |
|
| 547 |
The resulting :term:`dictionary <dict>` is constructed by merging ``opt`` dictionaries of all layers. |
| 548 |
If multiple layers define the same key, the value from the closest layer to the response handler will take precedence. |
| 549 |
|
| 550 |
.. _signature_namespace: |
| 551 |
|
| 552 |
Signature :term:`namespace` |
| 553 |
--------------------------- |
| 554 |
|
| 555 |
Litestar produces a model of the arguments to any handler or dependency function, called a "signature model" which is |
| 556 |
used for parsing and validation of raw data to be injected into the function. |
| 557 |
|
| 558 |
Building the model requires inspection of the names and types of the signature parameters at runtime, and so it is |
| 559 |
necessary for the types to be available within the scope of the module - something that linting tools such as ``ruff`` |
| 560 |
or ``flake8-type-checking`` will actively monitor, and suggest against. |
| 561 |
|
| 562 |
For example, the name ``Model`` is *not* available at runtime in the following snippet: |
| 563 |
|
| 564 |
.. code-block:: python |
| 565 |
:caption: A route handler with a type that is not available at runtime |
| 566 |
|
| 567 |
from __future__ import annotations |
| 568 |
|
| 569 |
from typing import TYPE_CHECKING |
| 570 |
|
| 571 |
from litestar import Controller, post |
| 572 |
|
| 573 |
if TYPE_CHECKING: |
| 574 |
from domain import Model |
| 575 |
|
| 576 |
|
| 577 |
class MyController(Controller): |
| 578 |
@post() |
| 579 |
def create_item(data: Model) -> Model: |
| 580 |
return data |
| 581 |
|
| 582 |
In this example, Litestar will be unable to generate the signature model because the type ``Model`` does not exist in |
| 583 |
the module scope at runtime. We can address this on a case-by-case basis by silencing our linters, for example: |
| 584 |
|
| 585 |
.. code-block:: python |
| 586 |
:no-upgrade: |
| 587 |
:caption: Silencing linters for a type that is not available at runtime |
| 588 |
|
| 589 |
from __future__ import annotations |
| 590 |
|
| 591 |
from typing import TYPE_CHECKING |
| 592 |
|
| 593 |
from litestar import Controller, post |
| 594 |
|
| 595 |
# Choose the appropriate noqa directive according to your linter |
| 596 |
from domain import Model # noqa: TCH002 |
| 597 |
|
| 598 |
However, this approach can get tedious; as an alternative, Litestar accepts a ``signature_types`` sequence at |
| 599 |
every :ref:`layer <layered-architecture>` of the application, as demonstrated in the following example: |
| 600 |
|
| 601 |
.. literalinclude:: /examples/signature_namespace/domain.py |
| 602 |
:language: python |
| 603 |
:caption: This module defines our domain type in some central place. |
| 604 |
|
| 605 |
This module defines our controller, note that we do not import ``Model`` into the runtime :term:`namespace`, |
| 606 |
nor do we require any directives to control behavior of linters. |
| 607 |
|
| 608 |
.. literalinclude:: /examples/signature_namespace/controller.py |
| 609 |
:language: python |
| 610 |
:caption: This module defines our controller without importing ``Model`` into the runtime namespace. |
| 611 |
|
| 612 |
Finally, we ensure that our application knows that when it encounters the name "Model" when parsing signatures, that it |
| 613 |
should reference our domain ``Model`` type. |
| 614 |
|
| 615 |
.. literalinclude:: /examples/signature_namespace/app.py |
| 616 |
:language: python |
| 617 |
:caption: Ensuring the application knows how to resolve the ``Model`` type when parsing signatures. |
| 618 |
|
| 619 |
.. tip:: If you want to map your type to a name that is different from its ``__name__`` attribute, |
| 620 |
you can use the :paramref:`~.handlers.base.BaseRouteHandler.signature_namespace` parameter, |
| 621 |
e.g., ``app = Litestar(signature_namespace={"FooModel": Model})``. |
| 622 |
|
| 623 |
This enables import patterns like ``from domain.foo import Model as FooModel`` inside ``if TYPE_CHECKING`` blocks. |
| 624 |
|
| 625 |
Default signature :term:`namespace` |
| 626 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 627 |
|
| 628 |
Litestar automatically adds some names to the signature :term:`namespace` when parsing signature models in |
| 629 |
order to support injection of the :ref:`handler-function-kwargs`. |
| 630 |
|
| 631 |
These names are: |
| 632 |
|
| 633 |
* ``Headers`` |
| 634 |
* ``ImmutableState`` |
| 635 |
* ``Receive`` |
| 636 |
* ``Request`` |
| 637 |
* ``Scope`` |
| 638 |
* ``Send`` |
| 639 |
* ``State`` |
| 640 |
* ``WebSocket`` |
| 641 |
* ``WebSocketScope`` |
| 642 |
|
| 643 |
The import of any of these names can be safely left inside an ``if TYPE_CHECKING:`` block without any configuration |
| 644 |
required. |