Debian Codegraph @

docs/usage/routing/overview.rst

raw
1 ========
2 Overview
3 ========
4
5 Registering Routes
6 -------------------
7
8 At the root of every Litestar application there is an instance of the :class:`Litestar <litestar.app.Litestar>` class,
9 on which the root level :class:`controllers <.controller.Controller>`, :class:`routers <.router.Router>`,
10 and :class:`route handler <.handlers.BaseRouteHandler>` functions are registered using the
11 :paramref:`~litestar.config.app.AppConfig.route_handlers` :term:`kwarg <argument>`:
12
13 .. code-block:: python
14 :caption: Registering route handlers
15
16 from litestar import Litestar, get
17
18
19 @get("/sub-path")
20 def sub_path_handler() -> None: ...
21
22
23 @get()
24 def root_handler() -> None: ...
25
26
27 app = Litestar(route_handlers=[root_handler, sub_path_handler])
28
29 Components registered on the app are appended to the root path. Thus, the ``root_handler`` function will be called for
30 the path ``"/"``, whereas the ``sub_path_handler`` will be called for ``"/sub-path"``.
31
32 You can also declare a function to handle multiple paths, e.g.:
33
34 .. code-block:: python
35 :caption: Registering a route handler for multiple paths
36
37 from litestar import get, Litestar
38
39
40 @get(["/", "/sub-path"])
41 def handler() -> None: ...
42
43
44 app = Litestar(route_handlers=[handler])
45
46 To handle more complex path schemas you should use :class:`controllers <.controller.Controller>` and
47 :class:`routers <.router.Router>`
48
49 Registering routes dynamically
50 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
51
52 Occasionally there is a need for dynamic route registration. Litestar supports this via the
53 :paramref:`~.app.Litestar.register` method exposed by the Litestar app instance:
54
55 .. code-block:: python
56 :caption: Registering a route handler dynamically with the :paramref:`~.app.Litestar.register` method
57
58 from litestar import Litestar, get
59
60
61 @get()
62 def root_handler() -> None: ...
63
64
65 app = Litestar(route_handlers=[root_handler])
66
67
68 @get("/sub-path")
69 def sub_path_handler() -> None: ...
70
71
72 app.register(sub_path_handler)
73
74 Since the app instance is attached to all instances of :class:`~.connection.base.ASGIConnection`,
75 :class:`~.connection.request.Request`, and :class:`~.connection.websocket.WebSocket` objects, you can in
76 effect call the :meth:`~.router.Router.register` method inside route handler functions, middlewares, and even
77 injected dependencies. For example:
78
79 .. code-block:: python
80 :caption: Call the :meth:`~.router.Router.register` method from inside a route handler function
81
82 from typing import Any
83 from litestar import Litestar, Request, get
84
85
86 @get("/some-path")
87 def route_handler(request: Request[Any, Any]) -> None:
88 @get("/sub-path")
89 def sub_path_handler() -> None: ...
90
91 request.app.register(sub_path_handler)
92
93
94 app = Litestar(route_handlers=[route_handler])
95
96 In the above we dynamically created the ``sub_path_handler`` and registered it inside the ``route_handler`` function.
97
98 .. caution:: Although Litestar exposes the :meth:`register <.router.Router.register>` method, it should not be abused.
99 Dynamic route registration increases the application complexity and makes it harder to reason about the code.
100 It should therefore be used only when absolutely required.
101
102 :class:`Routers <.router.Router>`
103 ---------------------------------
104
105 :class:`Routers <.router.Router>` are instances of the :class:`~.router.Router`,
106 class which is the base class for the :class:`Litestar app <.app.Litestar>` itself.
107
108 A :class:`~.router.Router` can register :class:`Controllers <.controller.Controller>`,
109 :class:`route handler <.handlers.BaseRouteHandler>` functions, and other routers, similarly to the Litestar constructor:
110
111 .. code-block:: python
112 :caption: Registering a :class:`~.router.Router`
113
114 from litestar import Litestar, Router, get
115
116
117 @get("/{order_id:int}")
118 def order_handler(order_id: int) -> None: ...
119
120
121 order_router = Router(path="/orders", route_handlers=[order_handler])
122 base_router = Router(path="/base", route_handlers=[order_router])
123 app = Litestar(route_handlers=[base_router])
124
125 Once ``order_router`` is registered on ``base_router``, the handler function registered on ``order_router`` will
126 become available on ``/base/orders/{order_id}``.
127
128 :class:`Controllers <.controller.Controller>`
129 ---------------------------------------------
130
131 :class:`Controllers <.controller.Controller>` are subclasses of the :class:`Controller <.controller.Controller>` class.
132 They are used to organize endpoints under a specific sub-path, which is the controller's path.
133 Their purpose is to allow users to utilize Python OOP for better code organization and organize code by logical concerns.
134
135 .. dropdown:: Click to see an example of registering a controller
136
137 .. code-block:: python
138 :caption: Registering a :class:`~.controller.Controller`
139
140 from litestar.plugins.pydantic import PydanticDTO
141 from litestar.controller import Controller
142 from litestar.dto import DTOConfig, DTOData
143 from litestar.handlers import get, post, patch, delete
144 from pydantic import BaseModel, UUID4
145
146
147 class UserOrder(BaseModel):
148 user_id: int
149 order: str
150
151
152 class PartialUserOrderDTO(PydanticDTO[UserOrder]):
153 config = DTOConfig(partial=True)
154
155
156 class UserOrderController(Controller):
157 path = "/user-order"
158
159 @post()
160 async def create_user_order(self, data: UserOrder) -> UserOrder: ...
161
162 @get(path="/{order_id:uuid}")
163 async def retrieve_user_order(self, order_id: UUID4) -> UserOrder: ...
164
165 @patch(path="/{order_id:uuid}", dto=PartialUserOrderDTO)
166 async def update_user_order(
167 self, order_id: UUID4, data: DTOData[PartialUserOrderDTO]
168 ) -> UserOrder: ...
169
170 @delete(path="/{order_id:uuid}")
171 async def delete_user_order(self, order_id: UUID4) -> None: ...
172
173 The above is a simple example of a "CRUD" controller for a model called ``UserOrder``. You can place as
174 many :doc:`route handler methods </usage/routing/handlers>` on a controller,
175 as long as the combination of path+http method is unique.
176
177 The ``path`` that is defined on the :class:`controller <.controller.Controller>` is appended before the path that is
178 defined for the route handlers declared on it. Thus, in the above example, ``create_user_order`` has the path of the
179 :class:`controller <.controller.Controller>` - ``/user-order/``, while ``retrieve_user_order`` has the path
180 ``/user-order/{order_id:uuid}"``.
181
182 .. note:: If you do not declare a ``path`` class variable on the controller, it will default to the root path of ``"/"``.
183
184 Registering components multiple times
185 --------------------------------------
186
187 You can register both standalone route handler functions and controllers multiple times.
188
189 Controllers
190 ^^^^^^^^^^^
191
192 .. code-block:: python
193 :caption: Registering a controller multiple times
194
195 from litestar import Router, Controller, get
196
197
198 class MyController(Controller):
199 path = "/controller"
200
201 @get()
202 def handler(self) -> None: ...
203
204
205 internal_router = Router(path="/internal", route_handlers=[MyController])
206 partner_router = Router(path="/partner", route_handlers=[MyController])
207 consumer_router = Router(path="/consumer", route_handlers=[MyController])
208
209 In the above, the same ``MyController`` class has been registered on three different routers. This is possible because
210 what is passed to the :class:`router <.router.Router>` is not a class instance but rather the class itself.
211 The :class:`router <.router.Router>` creates its own instance of the :class:`controller <.controller.Controller>`,
212 which ensures encapsulation.
213
214 Therefore, in the above example, three different instances of ``MyController`` will be created, each mounted on a
215 different sub-path, e.g., ``/internal/controller``, ``/partner/controller``, and ``/consumer/controller``.
216
217 Route handlers
218 ^^^^^^^^^^^^^^
219
220 You can also register standalone route handlers multiple times:
221
222 .. code-block:: python
223 :caption: Registering a route handler multiple times
224
225 from litestar import Litestar, Router, get
226
227
228 @get(path="/handler")
229 def my_route_handler() -> None: ...
230
231
232 internal_router = Router(path="/internal", route_handlers=[my_route_handler])
233 partner_router = Router(path="/partner", route_handlers=[my_route_handler])
234 consumer_router = Router(path="/consumer", route_handlers=[my_route_handler])
235
236 Litestar(route_handlers=[internal_router, partner_router, consumer_router])
237
238 When the handler function is registered, it's actually copied. Thus, each router has its own unique instance of
239 the route handler. Path behaviour is identical to that of controllers above, namely, the route handler
240 function will be accessible in the following paths: ``/internal/handler``, ``/partner/handler``, and ``/consumer/handler``.
241
242 .. attention:: You can nest routers as you see fit - but be aware that once a router has been registered it cannot be
243 re-registered or an exception will be raised.
244
245 Mounting ASGI Apps
246 -------------------
247
248 Litestar support "mounting" ASGI applications on sub-paths, i.e., specifying a handler function that will handle all
249 requests addressed to a given path.
250
251 .. dropdown:: Click to see an example of mounting an ASGI app
252
253 .. literalinclude:: /examples/routing/mount_custom_app.py
254 :language: python
255 :caption: Mounting an ASGI App
256
257 The handler function will receive all requests with an url that begins with ``/some/sub-path``, e.g, ``/some/sub-path``,
258 ``/some/sub-path/abc``, ``/some/sub-path/123/another/sub-path``, etc.
259
260 .. admonition:: Technical Details
261 :class: info
262
263 If we are sending a request to the above with the url ``/some/sub-path``, the handler will be invoked and
264 the value of ``scope["path"]`` will equal ``"/"``. If we send a request to ``/some/sub-path/abc``, it will also be
265 invoked,and ``scope["path"]`` will equal ``"/abc"``.
266
267 Mounting is especially useful when you need to combine components of other ASGI applications - for example, for third
268 party libraries. The following example is identical in principle to the one above, but it uses
269 `Starlette <https://www.starlette.io/>`_:
270
271 .. dropdown:: Click to see an example of mounting a Starlette app
272
273 .. literalinclude:: /examples/routing/mounting_starlette_app.py
274 :language: python
275 :caption: Mounting a Starlette App
276
277 .. admonition:: Why Litestar uses radix based routing
278
279 The regex matching used by popular frameworks such as Starlette, FastAPI or Flask is very good at
280 resolving path parameters fast, giving it an advantage when a URL has a lot of path parameters - what we can think
281 of as ``vertical`` scaling. On the other hand, it is not good at scaling horizontally - the more routes, the less
282 performant it becomes. Thus, there is an inverse relation between performance and application size with this
283 approach that strongly favors very small microservices. The **trie** based approach used by Litestar is agnostic to
284 the number of routes of the application giving it better horizontal scaling characteristics at the expense of
285 somewhat slower resolution of path parameters.
286
287 Litestar implements its routing solution that is based on the concept of a
288 `radix tree <https://en.wikipedia.org/wiki/Radix_tree>`_ or *trie*.
289
290 .. seealso:: If you are interested in the technical aspects of the implementation, refer to
291 `this GitHub issue <https://github.com/litestar-org/litestar/issues/177>`_ - it includes
292 an indepth discussion of the pertinent code.