Debian Codegraph @

docs/usage/responses.rst

raw
1 Responses
2 =========
3
4 Litestar allows for several ways in which HTTP responses can be specified and handled, each fitting a different use
5 case. The base pattern though is straightforward - simply return a value from a route handler function and let
6 Litestar take care of the rest:
7
8 .. code-block:: python
9
10 from pydantic import BaseModel
11 from litestar import get
12
13
14 class Resource(BaseModel):
15 id: int
16 name: str
17
18
19 @get("/resources")
20 def retrieve_resource() -> Resource:
21 return Resource(id=1, name="my resource")
22
23 In the example above, the route handler function returns an instance of the ``Resource`` pydantic class. This value will
24 then be used by Litestar to construct an instance of the :class:`Response <litestar.response.Response>`
25 class using defaults values: the response status code will be set to ``200`` and it's ``Content-Type`` header will be set
26 to ``application/json``. The ``Resource`` instance will be serialized into JSON and set as the response body.
27
28
29
30 Media Type
31 ----------
32
33 You do not have to specify the ``media_type`` kwarg in the route handler function if the response should be JSON. But
34 if you wish to return a response other than JSON, you should specify this value. You can use
35 the :class:`MediaType <litestar.enums.MediaType>` enum for this purpose:
36
37 .. code-block:: python
38
39 from litestar import MediaType, get
40
41
42 @get("/resources", media_type=MediaType.TEXT)
43 def retrieve_resource() -> str:
44 return "The rumbling rabbit ran around the rock"
45
46 The value of the ``media_type`` kwarg affects both the serialization of response data and the generation of OpenAPI docs.
47 The above example will cause Litestar to serialize the response as a simple bytes string with a ``Content-Type`` header
48 value of ``text/plain``. It will also set the corresponding values in the OpenAPI documentation.
49
50 MediaType has the following members:
51
52
53 * MediaType.JSON: ``application/json``
54 * MediaType.MessagePack: ``application/x-msgpack``
55 * MediaType.TEXT: ``text/plain``
56 * MediaType.HTML: ``text/html``
57
58 You can also set any `IANA referenced <https://www.iana.org/assignments/media-types/media-types.xhtml>`_ media type
59 string as the ``media_type``. While this will still affect the OpenAPI generation as expected, you might need to handle
60 serialization using either a :ref:`custom response <usage/responses:Custom Responses>` with serializer or by serializing
61 the value in the route handler function.
62
63 JSON responses
64 ++++++++++++++
65
66 As previously mentioned, the default ``media_type`` is ``MediaType.JSON``. which supports the following values:
67
68 * :doc:`dataclasses <python:library/dataclasses>`
69 * `pydantic dataclasses <https://docs.pydantic.dev/usage/dataclasses/>`_
70 * `pydantic models <https://docs.pydantic.dev/usage/models/>`_
71 * models from libraries that extend pydantic models
72 * :class:`UUIDs <uuid.UUID>`
73 * :doc:`datetime objects <python:library/datetime>`
74 * `msgspec.Struct <https://msgspec.devstructs.html>`_
75 * container types such as :class:`dict` or :class:`list` containing supported types
76
77 If you need to return other values and would like to extend serialization you can do
78 this :ref:`custom responses <usage/responses:Custom Responses>`.
79
80 You can also set an application media type string with the ``+json`` suffix
81 defined in `RFC 6839 <https://datatracker.ietf.org/doc/html/rfc6839#section-3.1>`_
82 as the ``media_type`` and it will be recognized and serialized as json.
83
84 For example, you can use ``application/vnd.example.resource+json``
85 and it will work just like json but have the appropriate content-type header
86 and show up in the generated OpenAPI schema.
87
88 .. literalinclude:: /examples/responses/json_suffix_responses.py
89 :language: python
90
91 MessagePack responses
92 +++++++++++++++++++++
93
94 In addition to JSON, Litestar offers support for the `MessagePack <https://msgpack.org/>`_
95 format which can be a time and space efficient alternative to JSON.
96
97 It supports all the same types as JSON serialization. To send a ``MessagePack`` response,
98 simply specify the media type as ``MediaType.MESSAGEPACK``\ :
99
100 .. code-block:: python
101
102 from typing import Dict
103 from litestar import get, MediaType
104
105
106 @get(path="/health-check", media_type=MediaType.MESSAGEPACK)
107 def health_check() -> Dict[str, str]:
108 return {"hello": "world"}
109
110 Plaintext responses
111 +++++++++++++++++++
112
113 For ``MediaType.TEXT``, route handlers should return a :class:`str` or :class:`bytes` value:
114
115 .. code-block:: python
116
117 from litestar import get, MediaType
118
119
120 @get(path="/health-check", media_type=MediaType.TEXT)
121 def health_check() -> str:
122 return "healthy"
123
124 HTML responses
125 ++++++++++++++
126
127 For ``MediaType.HTML``, route handlers should return a :class:`str` or :class:`bytes` value that contains HTML:
128
129 .. code-block:: python
130
131 from litestar import get, MediaType
132
133
134 @get(path="/page", media_type=MediaType.HTML)
135 def health_check() -> str:
136 return """
137 <html>
138 <body>
139 <div>
140 <span>Hello World!</span>
141 </div>
142 </body>
143 </html>
144 """
145
146 .. tip::
147
148 It's a good idea to use a :ref:`template engine <usage/templating:template engines>` for more complex HTML responses
149 and to write the template itself in a separate file rather than a string.
150
151
152 Content Negotiation
153 -------------------
154
155 If your handler can return data with different media types and you want to use
156 `Content Negotiation <https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation>`_
157 to allow the client to choose which type to return, you can use the
158 :attr:`Request.accept <litestar.connection.Request.accept>` property to
159 calculate the best matching return media type.
160
161 .. literalinclude:: /examples/responses/response_content.py
162 :language: python
163
164
165 Status Codes
166 ------------
167
168 You can control the response ``status_code`` by setting the corresponding kwarg to the desired value:
169
170 .. code-block:: python
171
172 from pydantic import BaseModel
173 from litestar import get
174 from litestar.status_codes import HTTP_202_ACCEPTED
175
176
177 class Resource(BaseModel):
178 id: int
179 name: str
180
181
182 @get("/resources", status_code=HTTP_202_ACCEPTED)
183 def retrieve_resource() -> Resource:
184 return Resource(id=1, name="my resource")
185
186 If ``status_code`` is not set by the user, the following defaults are used:
187
188
189 * POST: 201 (Created)
190 * DELETE: 204 (No Content)
191 * GET, PATCH, PUT: 200 (Ok)
192
193 .. attention::
194
195 For status codes < 100 or 204, 304 statuses, no response body is allowed. If you specify a return annotation other
196 than ``None``, an :class:`ImproperlyConfiguredException <litestar.exceptions.ImproperlyConfiguredException>` will be raised.
197
198 .. note::
199
200 When using the ``route`` decorator with multiple http methods, the default status code is ``200``.
201 The default for ``delete`` is ``204`` because by default it is assumed that delete operations return no data.
202 This though might not be the case in your implementation - so take care of setting it as you see fit.
203
204 .. tip::
205
206 While you can write integers as the value for ``status_code``, e.g. ``200``, it's best practice to use constants (also in
207 tests). Litestar includes easy to use statuses that are exported from ``litestar.status_codes``, e.g. ``HTTP_200_OK``
208 and ``HTTP_201_CREATED``. Another option is the :class:`http.HTTPStatus` enum from the standard library, which also offers
209 extra functionality.
210
211
212 Returning responses
213 -------------------
214
215 While the default response handling fits most use cases, in some cases you need to be able to return a response instance
216 directly.
217
218 Litestar allows you to return any class inheriting from the :class:`Response <litestar.response.Response>` class. Thus, the below
219 example will work perfectly fine:
220
221 .. literalinclude:: /examples/responses/returning_responses.py
222 :language: python
223
224
225 .. attention::
226
227 In the case of the builtin :class:`Template <litestar.response.Template>`,
228 :class:`File <litestar.response.File>`, :class:`Stream <litestar.response.Stream>`, and
229 :class:`Redirect <litestar.response.Redirect>` you should use the response "response containers", otherwise
230 OpenAPI documentation will not be generated correctly. For more details see the respective documentation sections:
231
232 - `Template responses`_
233 - `File responses`_
234 - `Streaming responses`_
235 - `Redirect responses`_
236
237
238 Annotating responses
239 ++++++++++++++++++++
240
241 As you can see above, the :class:`Response <litestar.response.Response>` class accepts a generic argument. This allows Litestar
242 to infer the response body when generating the OpenAPI docs.
243
244 .. note::
245
246 If the generic argument is not provided, and thus defaults to ``Any``, the OpenAPI docs will be imprecise. So make sure
247 to type this argument even when returning an empty or ``null`` body, i.e. use ``None``.
248
249 Returning ASGI Applications
250 +++++++++++++++++++++++++++
251
252 Litestar also supports returning ASGI applications directly, as you would responses. For example:
253
254 .. code-block:: python
255
256 from litestar import get
257 from litestar.types import ASGIApp, Receive, Scope, Send
258
259
260 @get("/")
261 def handler() -> ASGIApp:
262 async def my_asgi_app(scope: Scope, receive: Receive, send: Send) -> None: ...
263
264 return my_asgi_app
265
266 What is an ASGI Application?
267 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
268
269 An ASGI application in this context is any async callable (function, class method or simply a class that implements
270 that special :meth:`object.__call__` dunder method) that accepts the three ASGI arguments: ``scope``, ``receive``, and
271 ``send``.
272
273 For example, all the following examples are ASGI applications:
274
275 Function ASGI Application
276 ~~~~~~~~~~~~~~~~~~~~~~~~~
277
278 .. code-block:: python
279
280 from litestar.types import Receive, Scope, Send
281
282
283 async def my_asgi_app_function(scope: Scope, receive: Receive, send: Send) -> None:
284 # do something here
285 ...
286
287 Method ASGI Application
288 ~~~~~~~~~~~~~~~~~~~~~~~
289
290 .. code-block:: python
291
292 from litestar.types import Receive, Scope, Send
293
294
295 class MyClass:
296 async def my_asgi_app_method(
297 self, scope: Scope, receive: Receive, send: Send
298 ) -> None:
299 # do something here
300 ...
301
302 Class ASGI Application
303 ~~~~~~~~~~~~~~~~~~~~~~
304
305 .. code-block:: python
306
307 from litestar.types import Receive, Scope, Send
308
309
310 class ASGIApp:
311 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
312 # do something here
313 ...
314
315 Returning responses from third party libraries
316 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
317
318 Because you can return any ASGI Application from a route handler, you can also use any ASGI application from other
319 libraries. For example, you can return the response classes from Starlette or FastAPI directly from route handlers:
320
321 .. code-block:: python
322
323 from starlette.responses import JSONResponse
324
325 from litestar import get
326 from litestar.types import ASGIApp
327
328
329 @get("/")
330 def handler() -> ASGIApp:
331 return JSONResponse(content={"hello": "world"}) # type: ignore
332
333 .. attention::
334
335 Litestar offers strong typing for the ASGI arguments. Other libraries often offer less strict typing, which might
336 cause type checkers to complain when using ASGI apps from them inside Litestar.
337 For the time being, the only solution is to add ``# type: ignore`` comments in the pertinent places.
338 Nonetheless, the above example will work perfectly fine.
339
340
341 Setting Response Headers
342 -------------------------
343
344 Litestar allows you to define response headers by using the ``response_headers`` kwarg. This kwarg is
345 available on all layers of the app - individual route handlers, controllers, routers, and the app
346 itself:
347
348 .. literalinclude:: /examples/responses/response_headers_1.py
349 :language: python
350
351
352 In the above example the response returned from ``my_route_handler`` will have headers set from each layer of the
353 application using the given key+value combinations. I.e. it will be a dictionary equal to this:
354
355 .. code-block:: json
356
357 {
358 "my-local-header": "local header",
359 "controller-level-header": "controller header",
360 "router-level-header": "router header",
361 "app-level-header": "app header"
362 }
363
364 The respective descriptions will be used for the OpenAPI documentation.
365
366
367 .. tip::
368
369 :class:`ResponseHeader <litestar.datastructures.response_header.ResponseHeader>` is
370 a special class that allows to add OpenAPI attributes such as `description` or `documentation_only`.
371 If you don't need those, you can optionally define `response_headers` using a mapping - such as a dictionary -
372 as well:
373
374 .. code-block:: python
375
376 @get(response_headers={"my-header": "header-value"})
377 async def handler() -> str: ...
378
379
380
381 Setting Headers Dynamically
382 +++++++++++++++++++++++++++
383
384 The above detailed scheme works great for statically configured headers, but how would you go about handling dynamically
385 setting headers? Litestar allows you to set headers dynamically in several ways and below we will detail the two
386 primary patterns.
387
388 Using Annotated Responses
389 ^^^^^^^^^^^^^^^^^^^^^^^^^
390
391 We can simply return a response instance directly from the route handler and set the headers dictionary manually
392 as you see fit, e.g.:
393
394 .. literalinclude:: /examples/responses/response_headers_2.py
395 :language: python
396
397
398 In the above we use the ``response_headers`` kwarg to pass the ``name`` and ``description`` parameters for the ``Random-Header``
399 to the OpenAPI documentation, but we set the value dynamically in as part of
400 the :ref:`annotated response <usage/responses:annotating responses>` we return. To this end we do not set a ``value``
401 for it and we designate it as ``documentation_only=True``.
402
403 Using the After Request Hook
404 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
405
406 An alternative pattern would be to use an :ref:`after request handler <after_request>`. We can define
407 the handler on different layers of the application as explained in the pertinent docs. We should take care to document
408 the headers on the corresponding layer:
409
410 .. literalinclude:: /examples/responses/response_headers_3.py
411 :language: python
412
413
414 In the above we set the response header using an ``after_request_handler`` function on the router level. Because the
415 handler function is applied on the router, we also set the documentation for it on the router.
416
417 We can use this pattern to fine-tune the OpenAPI documentation more granularly by overriding header specification as
418 required. For example, lets say we have a router level header being set and a local header with the same key but a
419 different value range:
420
421 .. literalinclude:: /examples/responses/response_headers_4.py
422 :language: python
423
424
425 Predefined Headers
426 ++++++++++++++++++
427
428 Litestar has a dedicated implementation for a few commonly used headers. These headers can be set separately
429 with dedicated keyword arguments or as class attributes on all layers of the app (individual route handlers, controllers,
430 routers, and the app itself). Each layer overrides the layer above it - thus, the headers defined for a specific route
431 handler will override those defined on its router, which will in turn override those defined on the app level.
432
433 These header implementations allow easy creating, serialization and parsing according to the associated header
434 specifications.
435
436 Cache Control
437 ^^^^^^^^^^^^^
438
439 :class:`CacheControlHeader <.datastructures.headers.CacheControlHeader>` represents a
440 `Cache-Control Header <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control>`_.
441
442 Here is a simple example that shows how to use it:
443
444 .. literalinclude:: /examples/datastructures/headers/cache_control.py
445 :caption: Cache Control Header
446 :language: python
447
448
449 In this example we have a ``cache-control`` with ``max-age`` of 1 month for the whole app, a ``max-age`` of
450 1 day for all routes within ``MyController``, and ``no-store`` for one specific route ``get_server_time``. Here are the cache
451 control values that will be returned from each endpoint:
452
453
454 * When calling ``/population`` the response will have ``cache-control`` with ``max-age=2628288`` (1 month).
455 * When calling ``/chance_of_rain`` the response will have ``cache-control`` with ``max-age=86400`` (1 day).
456 * When calling ``/timestamp`` the response will have ``cache-control`` with ``no-store`` which means don't store the result
457 in any cache.
458
459 ETag
460 ^^^^
461
462 :class:`ETag <.datastructures.headers.ETag>` represents an
463 `ETag header <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag>`_.
464
465 Here are some usage examples:
466
467 .. literalinclude:: /examples/datastructures/headers/etag.py
468 :caption: Returning ETag headers
469 :language: python
470
471
472 .. literalinclude:: /examples/datastructures/headers/etag_parsing.py
473 :caption: Parsing ETag headers
474 :language: python
475
476
477 Setting Response Cookies
478 -------------------------
479
480 Litestar allows you to define response cookies by using the ``response_cookies`` kwarg. This kwarg is
481 available on all layers of the app - individual route handlers, controllers, routers, and the app
482 itself:
483
484 .. literalinclude:: /examples/responses/response_cookies_1.py
485 :language: python
486
487
488 In the above example, the response returned by ``my_route_handler`` will have cookies set by each layer of the
489 application. Cookies are set using
490 the `Set-Cookie header <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie>`_ and with above resulting
491 in:
492
493 .. code-block:: text
494
495 Set-Cookie: local-cookie=local value; Path=/; SameSite=lax
496 Set-Cookie: controller-cookie=controller value; Path=/; SameSite=lax
497 Set-Cookie: router-cookie=router value; Path=/; SameSite=lax
498 Set-Cookie: app-cookie=app value; Path=/; SameSite=lax
499
500 You can easily override cookies declared in higher levels by redeclaring a cookie with the same key in a lower level,
501 e.g.:
502
503 .. literalinclude:: /examples/responses/response_cookies_2.py
504 :language: python
505
506
507 Of the two declarations of ``my-cookie`` only the route handler one will be used, because its lower level:
508
509 .. code-block:: text
510
511 Set-Cookie: my-cookie=456; Path=/; SameSite=lax
512
513
514
515 .. tip::
516
517 If all you need for your cookies are key and value, you can supply them using a :class:`Mapping[str, str] <typing.Mapping>`
518 - like a :class:`dict` - instead:
519
520 .. code-block:: python
521
522 @get(response_cookies={"my-cookie": "cookie-value"})
523 async def handler() -> str: ...
524
525
526 .. seealso::
527
528 * :class:`Cookie reference <.datastructures.cookie.Cookie>`
529
530
531
532 Setting Cookies dynamically
533 ++++++++++++++++++++++++++++
534
535 While the above scheme works great for static cookie values, it doesn't allow for dynamic cookies. Because cookies are
536 fundamentally a type of response header, we can utilize the same patterns we use to
537 setting :ref:`set headers headers <usage/responses:setting headers dynamically>`.
538
539 Using Annotated Responses
540 ^^^^^^^^^^^^^^^^^^^^^^^^^
541
542 We can simply return a response instance directly from the route handler and set the cookies list manually
543 as you see fit, e.g.:
544
545 .. literalinclude:: /examples/responses/response_cookies_3.py
546 :language: python
547
548
549 In the above we use the ``response_cookies`` kwarg to pass the ``key`` and ``description`` parameters for the ``Random-Cookie``
550 to the OpenAPI documentation, but we set the value dynamically in as part of
551 the :ref:`annotated response <usage/responses:annotating responses>` we return. To this end we do not set a ``value``
552 for it and we designate it as ``documentation_only=True``.
553
554 Using the After Request Hook
555 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
556
557 An alternative pattern would be to use an :ref:`after request handler <after_request>`. We can define
558 the handler on different layers of the application as explained in the pertinent docs. We should take care to document
559 the cookies on the corresponding layer:
560
561 .. literalinclude:: /examples/responses/response_cookies_4.py
562 :language: python
563
564
565 In the above we set the cookie using an ``after_request_handler`` function on the router level. Because the
566 handler function is applied on the router, we also set the documentation for it on the router.
567
568 We can use this pattern to fine-tune the OpenAPI documentation more granular by overriding cookie specification as
569 required. For example, lets say we have a router level cookie being set and a local cookie with the same key but a
570 different value range:
571
572 .. literalinclude:: /examples/responses/response_cookies_5.py
573 :language: python
574
575
576 Redirect Responses
577 ------------------
578
579 Redirect responses are `special HTTP responses <https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections>`_ with a
580 status code in the 30x range.
581
582 In Litestar, a redirect response looks like this:
583
584 .. code-block:: python
585
586 from litestar.status_codes import HTTP_302_FOUND
587 from litestar import get
588 from litestar.response import Redirect
589
590
591 @get(path="/some-path", status_code=HTTP_302_FOUND)
592 def redirect() -> Redirect:
593 # do some stuff here
594 # ...
595 # finally return redirect
596 return Redirect(path="/other-path")
597
598 To return a redirect response you should do the following:
599
600 - optionally: set an appropriate status code for the route handler (301, 302, 303, 307, 308). If not set the default of 302 will be used.
601 - annotate the return value of the route handler as returning :class:`Redirect <.response.Redirect>`
602 - return an instance of the :class:`Redirect <.response.Redirect>` class with the desired redirect path
603
604 File Responses
605 --------------
606
607 File responses send a file:
608
609 .. code-block:: python
610
611 from pathlib import Path
612 from litestar import get
613 from litestar.response import File
614
615
616 @get(path="/file-download")
617 def handle_file_download() -> File:
618 return File(
619 path=Path(Path(__file__).resolve().parent, "report").with_suffix(".pdf"),
620 filename="report.pdf",
621 )
622
623 The :class:`File <.response.File>` class expects two kwargs:
624
625
626 * ``path``: path of the file to download.
627 * ``filename``: the filename to set in the response
628 `Content-Disposition <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition>`_
629 attachment.
630
631 .. attention::
632
633 When a route handler's return value is annotated with :class:`File <.response.File>`, the default
634 ``media_type`` for the route_handler is switched from :class:`MediaType.JSON <.enums.MediaType>` to
635 :class:`MediaType.TEXT <.enums.MediaType>` (i.e. ``"text/plain"``). If the file being sent has an
636 `IANA media type <https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types>`_, you should set it
637 as the value for ``media_type`` instead.
638
639 For example:
640
641 .. code-block:: python
642
643 from pathlib import Path
644 from litestar import get
645 from litestar.response import File
646
647
648 @get(path="/file-download", media_type="application/pdf")
649 def handle_file_download() -> File:
650 return File(
651 path=Path(Path(__file__).resolve().parent, "report").with_suffix(".pdf"),
652 filename="report.pdf",
653 )
654
655
656 Streaming Responses
657 -------------------
658
659 To return a streaming response use the :class:`Stream <.response.Stream>` class. The class
660 receives a single positional arg, that must be an iterator delivering the stream:
661
662 .. literalinclude:: /examples/responses/streaming_responses.py
663 :language: python
664
665
666 .. note::
667
668 You can use different kinds of values for the iterator. It can be a callable returning a sync or async generator,
669 a generator itself, a sync or async iterator class, or an instance of a sync or async iterator class.
670
671
672 Server Sent Event Responses
673 ---------------------------
674
675 To send `server-sent-events` or SSEs to the frontend, use the :class:`ServerSentEvent <.response.ServerSentEvent>`
676 class. The class receives a content arg. You can additionally specify ``event_type``, which is the
677 name of the event as declared in the browser, the ``event_id``, which sets the event source property, ``comment_message``,
678 which is used in for sending pings, and ``retry_duration``, which dictates the duration for retrying.
679
680 .. literalinclude:: /examples/responses/sse_responses.py
681 :language: python
682
683
684 .. note::
685
686 You can use different kinds of values for the iterator. It can be a callable returning a sync or async generator,
687 a generator itself, a sync or async iterator class, or an instance of a sync or async iterator class.
688
689 In your iterator function you can yield integers, strings or bytes, the message sent in that case will have ``message``
690 as the ``event_type`` if the ServerSentEvent has no ``event_type`` set, otherwise it will use the ``event_type``
691 specified, and the data will be the yielded value.
692
693 If you want to send a different event type, you can use a dictionary with the keys ``event_type`` and ``data`` or the :class:`ServerSentEventMessage <.response.ServerSentEventMessage>` class.
694
695 .. note::
696
697 You can further customize all the sse parameters, add comments, and set the retry duration by using the :class:`ServerSentEvent <.response.ServerSentEvent>` class directly or by using the :class:`ServerSentEventMessage <.response.ServerSentEventMessage>` or dictionaries with the appropriate keys.
698
699
700 Template Responses
701 ------------------
702
703 Template responses are used to render templates into HTML. To use a template response you must first
704 :ref:`register a template engine <usage/templating:registering a template engine>` on the application level. Once an
705 engine is in place, you can use a template response like so:
706
707 .. code-block:: python
708
709 from litestar import Request, get
710 from litestar.response import Template
711
712
713 @get(path="/info")
714 def info(request: Request) -> Template:
715 return Template(template_name="info.html", context={"user": request.user})
716
717 In the above example, :class:`Template <.response.Template>` is passed the template name, which is a
718 path like value, and a context dictionary that maps string keys into values that will be rendered in the template.
719
720 Custom Responses
721 ----------------
722
723 While Litestar supports the serialization of many types by default, sometimes you want to return something that's not
724 supported. In those cases it's convenient to make use of a custom response class.
725
726 The example below illustrates how to deal with :class:`MultiDict <.datastructures.MultiDict>`
727 instances.
728
729 .. literalinclude:: /examples/responses/custom_responses.py
730 :language: python
731
732 .. admonition:: Layered architecture
733 :class: seealso
734
735 Response classes are part of Litestar's layered architecture, which means you can
736 set a response class on every layer of the application. If you have set a response
737 class on multiple layers, the layer closest to the route handler will take precedence.
738
739 You can read more about this here: :ref:`usage/applications:layered architecture`
740
741 Background Tasks
742 ----------------
743
744 All Litestar responses allow passing in a ``background`` kwarg. This kwarg accepts either an instance of
745 :class:`BackgroundTask <.background_tasks.BackgroundTask>` or an instance of
746 :class:`BackgroundTasks <.background_tasks.BackgroundTasks>`, which wraps an iterable of
747 :class:`BackgroundTask <.background_tasks.BackgroundTask>` instances.
748
749 A background task is a sync or async callable (function, method, or class that implements the :meth:`object.__call__`
750 dunder method) that will be called after the response finishes sending the data.
751
752 Thus, in the following example the passed in background task will be executed after the response sends:
753
754 .. literalinclude:: /examples/responses/background_tasks_1.py
755 :caption: Background Task Passed into Response
756 :language: python
757
758 When the ``greeter`` handler is called, the logging task will be called with any ``*args`` and ``**kwargs`` passed into
759 the :class:`BackgroundTask <.background_tasks.BackgroundTask>`.
760
761 .. note::
762
763 In the above example ``"greeter"`` is an arg and ``message=f"was called with name {name}"`` is a kwarg.
764 The function signature of ``logging_task`` allows for this, so this should pose no problem.
765 :class:`BackgroundTask <.background_tasks.BackgroundTask>` is typed with :class:`ParamSpec <typing.ParamSpec>`,
766 enabling correct type checking for arguments and keyword arguments passed to it.
767
768 Route decorators (e.g. ``@get``, ``@post``, etc.) also allow passing in a background task with the ``background`` kwarg:
769
770 .. literalinclude:: /examples/responses/background_tasks_2.py
771 :caption: Background Task Passed into Decorator
772 :language: python
773
774
775 .. note::
776
777 Route handler arguments cannot be passed into background tasks when they are passed into decorators.
778
779 Executing Multiple Background Tasks
780 +++++++++++++++++++++++++++++++++++
781
782 You can also use the :class:`BackgroundTasks <.background_tasks.BackgroundTasks>` class and pass to it an iterable
783 (:class:`list`, :class:`tuple`, etc.) of :class:`BackgroundTask <.background_tasks.BackgroundTask>` instances:
784
785 .. literalinclude:: /examples/responses/background_tasks_3.py
786 :caption: Multiple Background Tasks
787 :language: python
788
789
790 :class:`BackgroundTasks <.background_tasks.BackgroundTasks>` class
791 accepts an optional keyword argument ``run_in_task_group`` with a default value of ``False``. Setting this to ``True``
792 allows background tasks to run concurrently, using an `anyio.task_group <https://anyio.readthedocs.io/en/stable/tasks.html>`_.
793
794 .. note::
795
796 Setting ``run_in_task_group`` to ``True`` will not preserve execution order.
797
798 Pagination
799 -----------
800
801 When you need to return a large number of items from an endpoint it is common practice to use pagination to ensure
802 clients can request a specific subset or "page" from the total dataset. Litestar supports three types of pagination out
803 of the box:
804
805 * classic pagination
806 * limit / offset pagination
807 * cursor pagination
808
809 Classic Pagination
810 ++++++++++++++++++
811
812 In classic pagination the dataset is divided into pages of a specific size and the consumer then requests a specific page.
813
814 .. literalinclude:: /examples/pagination/using_classic_pagination.py
815 :caption: Classic Pagination
816 :language: python
817
818 The data container for this pagination is called :class:`ClassicPagination <.pagination.ClassicPagination>`, which is
819 what will be returned by the paginator in the above example This will also generate the corresponding OpenAPI
820 documentation.
821
822 If you require async logic, you can implement
823 the :class:`AbstractAsyncClassicPaginator <.pagination.AbstractAsyncClassicPaginator>` instead of the
824 :class:`AbstractSyncClassicPaginator <.pagination.AbstractSyncClassicPaginator>`.
825
826 Offset Pagination
827 +++++++++++++++++
828
829 In offset pagination the consumer requests a number of items specified by ``limit`` and the ``offset`` from the beginning of the dataset.
830 For example, given a list of 50 items, you could request ``limit=10``, ``offset=39`` to request items 40-50.
831
832 .. literalinclude:: /examples/pagination/using_offset_pagination.py
833 :caption: Offset Pagination
834 :language: python
835
836 The data container for this pagination is
837 called :class:`OffsetPagination <.pagination.OffsetPagination>`, which is what will be returned by the paginator in the
838 above example This will also generate the corresponding OpenAPI documentation.
839
840 If you require async logic, you can implement
841 the :class:`AbstractAsyncOffsetPaginator <.pagination.AbstractAsyncOffsetPaginator>` instead of the
842 :class:`AbstractSyncOffsetPaginator <.pagination.AbstractSyncOffsetPaginator>`.
843
844 Offset Pagination With SQLAlchemy
845 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
846
847 When retrieving paginated data from the database using SQLAlchemy, the Paginator instance requires an SQLAlchemy session
848 instance to make queries. This can be achieved with :doc:`/usage/dependency-injection`
849
850 .. literalinclude:: /examples/pagination/using_offset_pagination_with_sqlalchemy.py
851 :caption: Offset Pagination With SQLAlchemy
852 :language: python
853
854 See :ref:`SQLAlchemy plugin <usage/databases/sqlalchemy/plugins/index:Plugins>` for sqlalchemy integration.
855
856 Cursor Pagination
857 +++++++++++++++++
858
859 In cursor pagination the consumer requests a number of items specified by ``results_per_page`` and a ``cursor`` after which results are given.
860 Cursor is unique identifier within the dataset that serves as a way to point the starting position.
861
862 .. literalinclude:: /examples/pagination/using_cursor_pagination.py
863 :caption: Cursor Pagination
864 :language: python
865
866 The data container for this pagination is called :class:`CursorPagination <.pagination.CursorPagination>`, which is what
867 will be returned by the paginator in the above example This will also generate the corresponding OpenAPI documentation.
868
869 If you require async logic, you can implement
870 the :class:`AbstractAsyncCursorPaginator <.pagination.AbstractAsyncCursorPaginator>` instead of the
871 :class:`AbstractSyncCursorPaginator <.pagination.AbstractSyncCursorPaginator>`.