handlers#
- class litestar.handlers.ASGIRouteHandler#
Bases:
BaseRouteHandlerASGI Route Handler decorator.
Use this decorator to decorate ASGI applications.
- __init__(path: str | Sequence[str] | None = None, *, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, is_mount: bool = False, is_static: bool = False, signature_namespace: Mapping[str, Any] | None = None, copy_scope: bool | None = None, **kwargs: Any) None#
Initialize
ASGIRouteHandler.- Parameters:
exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
name¶ – A string identifying the route handler.
opt¶ – A string key mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.path¶ – A path fragment for the route handler function or a list of path fragments. If not given defaults to
/is_mount¶ – A boolean dictating whether the handler’s paths should be regarded as mount paths. Mount path accept any arbitrary paths that begin with the defined prefixed path. For example, a mount with the path
/some-path/will accept requests for/some-path/and any sub path under this, e.g./some-path/sub-path/etc.is_static¶ – A boolean dictating whether the handler’s paths should be regarded as static paths. Static paths are used to deliver static files.
signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
copy_scope¶ – Copy the ASGI ‘scope’ before calling the mounted application. Should be set to ‘True’ unless side effects via scope mutations by the mounted ASGI application are intentional
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- class litestar.handlers.BaseRouteHandler#
Bases:
objectBase route handler.
Serves as a subclass for all route handlers
- __call__(fn: AsyncAnyCallable) Self#
Replace a function with itself.
- __init__(path: str | Sequence[str] | None = None, *, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, signature_types: Sequence[Any] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
HTTPRouteHandler.- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
signature_types¶ – A sequence of types for use in forward reference resolution during signature modelling. These types will be added to the signature namespace using their
__name__attribute.type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- async authorize_connection(connection: ASGIConnection) None#
Ensure the connection is authorized by running all the route guards in scope.
- create_kwargs_model(path_parameters: dict[str, PathParameterDefinition]) KwargsModel#
Create a KwargsModel for a given route handler.
- property default_deserializer: Callable[[Any, Any], Any]#
Get a default deserializer for the route handler.
- Returns:
A default deserializer for the route handler.
- property default_serializer: Callable[[Any], Any]#
Get a default serializer for the route handler.
- Returns:
A default serializer for the route handler.
- property dependency_name_set: set[str]#
Set of all dependency names provided in the handler’s ownership layers.
- property fn: AsyncAnyCallable#
Get the handler function.
- Raises:
ImproperlyConfiguredException – if handler fn is not set.
- Returns:
Handler function
- property handler_name: str#
Get the name of the handler function.
- Raises:
ImproperlyConfiguredException – if handler fn is not set.
- Returns:
Name of the handler function
- property ownership_layers: list[Self | Controller | Router]#
Return the handler layers from the app down to the route handler.
app -> ... -> route handler
- property parsed_fn_signature: ParsedSignature#
Return the parsed signature of the handler function.
This method is memoized so the computation occurs only once.
- Returns:
A ParsedSignature instance
- resolve_data_dto() type[AbstractDTO] | None#
Resolve the data_dto by starting from the route handler and moving up. If a handler is found it is returned, otherwise None is set. This method is memoized so the computation occurs only once.
- Returns:
An optional
DTO type
- resolve_dependencies() dict[str, Provide]#
Return all dependencies correlating to handler function’s kwargs that exist in the handler’s scope.
- resolve_exception_handlers() ExceptionHandlersMap#
Resolve the exception_handlers by starting from the route handler and moving up.
This method is memoized so the computation occurs only once.
- resolve_guards() list[Guard]#
Return all guards in the handlers scope, starting from highest to current layer.
- resolve_layered_parameters() dict[str, FieldDefinition]#
Return all parameters declared above the handler.
- resolve_middleware() list[Middleware]#
Build the middleware stack for the RouteHandler and return it.
The middlewares are added from top to bottom (
app -> router -> controller -> route handler) and then reversed.
- resolve_opts() None#
Build the route handler opt dictionary by going from top to bottom.
When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the layer closest to the response handler will take precedence.
- resolve_return_dto() type[AbstractDTO] | None#
Resolve the return_dto by starting from the route handler and moving up. If a handler is found it is returned, otherwise None is set. This method is memoized so the computation occurs only once.
- Returns:
An optional
DTO type
- resolve_signature_namespace() dict[str, Any]#
Build the route handler signature namespace dictionary by going from top to bottom.
When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the layer closest to the response handler will take precedence.
- resolve_type_decoders() Sequence[tuple[Callable[[Any], bool], Callable[[Any, Any], Any]]]#
Return a merged type_encoders mapping.
This method is memoized so the computation occurs only once.
- Returns:
A dict of type encoders
- class litestar.handlers.HTTPRouteHandler#
Bases:
BaseRouteHandlerHTTP Route Decorator.
Use this decorator to decorate an HTTP handler with multiple methods.
- __call__(fn: Callable[[...], Any]) HTTPRouteHandler#
Replace a function with itself.
- __init__(path: str | Sequence[str] | None = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, http_method: HttpMethod | Method | Sequence[HttpMethod | Method], media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, request_max_body_size: int | None | EmptyType = _EmptyEnum.EMPTY, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, signature_namespace: Mapping[str, Any] | None = None, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
HTTPRouteHandler.- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.request_max_body_size¶ – Maximum allowed size of the request body in bytes. If this size is exceeded, a ‘413 - Request Entity Too Large’ error response is returned.
response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200forGET,PUTandPATCH,201forPOSTand204forDELETE. For mixed method requests it will check forPOSTandDELETEfirst then defaults to200.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
"base64".content_media_type¶ – A string designating the media-type of the content, e.g.
"image/png".deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- get_response_handler(is_response_type_data: bool = False) Callable[[Any], Awaitable[ASGIApp]]#
Resolve the response_handler function for the route handler.
This method is memoized so the computation occurs only once.
- Parameters:
is_response_type_data¶ – Whether to return a handler for ‘Response’ instances.
- Returns:
Async Callable to handle an HTTP Request
- resolve_after_response() AsyncAnyCallable | None#
Resolve the after_response handler by starting from the route handler and moving up.
If a handler is found it is returned, otherwise None is set. This method is memoized so the computation occurs only once.
- Returns:
An optional
after response lifecycle hook handler
- resolve_before_request() AsyncAnyCallable | None#
Resolve the before_handler handler by starting from the route handler and moving up.
If a handler is found it is returned, otherwise None is set. This method is memoized so the computation occurs only once.
- Returns:
An optional
before request lifecycle hook handler
- resolve_include_in_schema() bool#
Resolve the ‘include_in_schema’ property by starting from the route handler and moving up.
If ‘include_in_schema’ is found in any of the ownership layers, the last value found is returned. If not found in any layer, the default value
Trueis returned.- Returns:
The resolved ‘include_in_schema’ property.
- Return type:
- resolve_request_class() type[Request]#
Return the closest custom Request class in the owner graph or the default Request class.
This method is memoized so the computation occurs only once.
- Returns:
The default
Requestclass for the route handler.
- resolve_response_class() type[Response]#
Return the closest custom Response class in the owner graph or the default Response class.
This method is memoized so the computation occurs only once.
- Returns:
The default
Responseclass for the route handler.
- resolve_response_cookies() frozenset[Cookie]#
Return a list of Cookie instances. Filters the list to ensure each cookie key is unique.
- Returns:
A list of
Cookieinstances.
- resolve_response_headers() frozenset[ResponseHeader]#
Return all header parameters in the scope of the handler function.
- Returns:
A dictionary mapping keys to
ResponseHeaderinstances.
- resolve_security() list[SecurityRequirement]#
Resolve the security property by starting from the route handler and moving up.
Security requirements are additive, so the security requirements of the route handler are the sum of all security requirements of the ownership layers.
- Returns:
The resolved security property.
- Return type:
- resolve_tags() list[str]#
Resolve the tags property by starting from the route handler and moving up.
Tags are additive, so the tags of the route handler are the sum of all tags of the ownership layers.
- class litestar.handlers.WebsocketListener#
Bases:
ABC- dependencies: Dependencies | None = None#
A string keyed mapping of dependency
Providerinstances.
- dto: type[AbstractDTO] | None | EmptyType = 0#
AbstractDTOto use for (de)serializing and validation of request data
- exception_handlers: dict[int | type[Exception], ExceptionHandler] | None = None#
A mapping of status codes and/or exception types to handler functions.
- middleware: list[Middleware] | None = None#
A sequence of
Middleware.
- on_accept(*args: Any, **kwargs: Any) Any#
Called after a
WebSocketconnection has been accepted. Can receive any dependencies
- on_disconnect(*args: Any, **kwargs: Any) Any#
Called after a
WebSocketconnection has been disconnected. Can receive any dependencies
- abstractmethod on_receive(*args: Any, **kwargs: Any) Any#
Called after data has been received from the WebSocket.
This should take a
dataargument, receiving the processed WebSocket data, and can additionally include handler dependencies such asstate, or other regular dependencies.Data returned from this function will be serialized and sent via the socket according to handler configuration.
- opt: dict[str, Any] | None = None#
A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.
- path: str | list[str] | None = None#
A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/
- return_dto: type[AbstractDTO] | None | EmptyType = 0#
AbstractDTOto use for serializing outbound response data.
- send_mode: WebSocketMode = 'text'#
Websocket mode to send data in, either text or binary.
- signature_namespace: Mapping[str, Any] | None = None#
A mapping of names to types for use in forward reference resolution during signature modelling.
- type_decoders: TypeDecodersSequence | None = None#
A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
- Type:
- type_encoders: TypeEncodersMap | None = None#
A mapping of types to callables that transform them into types supported for serialization.
- Type:
- class litestar.handlers.WebsocketListenerRouteHandler#
Bases:
WebsocketRouteHandlerA websocket listener that automatically accepts a connection, handles disconnects, invokes a callback function every time new data is received and sends any data returned
- connection_accept_handler#
Callback to accept a WebSocket connection. By default, calls WebSocket.accept
- on_accept#
Callback invoked after a WebSocket connection has been accepted
- on_disconnect#
Callback invoked after a WebSocket connection has been closed
- __init__(path: str | list[str] | None = None, *, connection_accept_handler: Callable[[WebSocket], Coroutine[Any, Any, None]] = <function WebSocket.accept>, connection_lifespan: Callable[..., AbstractAsyncContextManager[Any]] | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, exception_handlers: dict[int | type[Exception], ExceptionHandler] | None = None, guards: list[Guard] | None = None, middleware: list[Middleware] | None = None, receive_mode: WebSocketMode = 'text', send_mode: WebSocketMode = 'text', name: str | None = None, on_accept: AnyCallable | None = None, on_disconnect: AnyCallable | None = None, opt: dict[str, Any] | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[WebSocket] | None = None, **kwargs: Any) None#
Initialize
WebsocketRouteHandler- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/connection_accept_handler¶ – A callable that accepts a
WebSocketinstance and returns a coroutine that when awaited, will accept the connection. Defaults toWebSocket.accept.connection_lifespan¶ – An asynchronous context manager, handling the lifespan of the connection. By default, it calls the
connection_accept_handler,on_connectandon_disconnect. Can request any dependencies, for example theWebSocketconnectiondependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
middleware¶ – A sequence of
Middleware.receive_mode¶ – Websocket mode to receive data in, either text or binary.
send_mode¶ – Websocket mode to receive data in, either text or binary.
name¶ – A string identifying the route handler.
on_accept¶ – Callback invoked after a connection has been accepted. Can request any dependencies, for example the
WebSocketconnectionon_disconnect¶ – Callback invoked after a connection has been closed. Can request any dependencies, for example the
WebSocketconnectionopt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
websocket_class¶ – A custom subclass of
WebSocketto be used as route handler’s default websocket class.
- default_connection_lifespan(socket: WebSocket, on_accept_dependencies: Dict[str, Any] | None = None, on_disconnect_dependencies: Dict[str, Any] | None = None) AsyncGenerator[None, None]#
Handle the connection lifespan of a
WebSocket.- Parameters:
By, default this will
Call
connection_accept_handlerto accept a connectionCall
on_acceptif defined after a connection has been acceptedCall
on_disconnectupon leaving the context
- class litestar.handlers.WebsocketRouteHandler#
Bases:
BaseRouteHandlerWebsocket route handler decorator.
Use this decorator to decorate websocket handler functions.
- __init__(path: str | list[str] | None = None, *, dependencies: Dependencies | None = None, exception_handlers: dict[int | type[Exception], ExceptionHandler] | None = None, guards: list[Guard] | None = None, middleware: list[Middleware] | None = None, name: str | None = None, opt: dict[str, Any] | None = None, signature_namespace: Mapping[str, Any] | None = None, websocket_class: type[WebSocket] | None = None, **kwargs: Any) None#
Initialize
WebsocketRouteHandler- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/dependencies¶ – A string keyed mapping of dependency
Providerinstances.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
websocket_class¶ – A custom subclass of
WebSocketto be used as route handler’s default websocket class.**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- litestar.handlers.asgi#
alias of
ASGIRouteHandler
- class litestar.handlers.delete#
Bases:
HTTPRouteHandlerDELETE Route Decorator.
Use this decorator to decorate an HTTP handler for DELETE requests.
- __init__(path: str | None | Sequence[str] = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
delete- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
connection.Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.dependencies¶ – A string keyed mapping of dependency
Providerinstances.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200for mixed method orGET,PUTandPATCH,201forPOSTand204forDELETE.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
base64.content_media_type¶ – A string designating the media-type of the content, e.g.
image/png.deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- class litestar.handlers.get#
Bases:
HTTPRouteHandlerGET Route Decorator.
Use this decorator to decorate an HTTP handler for GET requests.
- __init__(path: str | None | Sequence[str] = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
get.- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
connection.Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200for mixed method orGET,PUTandPATCH,201forPOSTand204forDELETE.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
base64.content_media_type¶ – A string designating the media-type of the content, e.g.
image/png.deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- class litestar.handlers.head#
Bases:
HTTPRouteHandlerHEAD Route Decorator.
Use this decorator to decorate an HTTP handler for HEAD requests.
- __init__(path: str | None | Sequence[str] = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, signature_namespace: Mapping[str, Any] | None = None, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
head.Notes
- A response to a head request cannot include a body.
See: [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD).
- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
connection.Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200for mixed method orGET,PUTandPATCH,201forPOSTand204forDELETE.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
base64.content_media_type¶ – A string designating the media-type of the content, e.g.
image/png.deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- class litestar.handlers.patch#
Bases:
HTTPRouteHandlerPATCH Route Decorator.
Use this decorator to decorate an HTTP handler for PATCH requests.
- __init__(path: str | None | Sequence[str] = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, request_max_body_size: int | None | EmptyType = _EmptyEnum.EMPTY, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
patch.- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
connection.Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.request_max_body_size¶ – Maximum allowed size of the request body in bytes. If this size is exceeded, a ‘413 - Request Entity Too Large’ error response is returned.
response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200for mixed method orGET,PUTandPATCH,201forPOSTand204forDELETE.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
base64.content_media_type¶ – A string designating the media-type of the content, e.g.
image/png.deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- class litestar.handlers.post#
Bases:
HTTPRouteHandlerPOST Route Decorator.
Use this decorator to decorate an HTTP handler for POST requests.
- __init__(path: str | None | Sequence[str] = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, request_max_body_size: int | None | EmptyType = _EmptyEnum.EMPTY, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
post- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
connection.Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.request_max_body_size¶ – Maximum allowed size of the request body in bytes. If this size is exceeded, a ‘413 - Request Entity Too Large’ error response is returned.
response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200for mixed method orGET,PUTandPATCH,201forPOSTand204forDELETE.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
base64.content_media_type¶ – A string designating the media-type of the content, e.g.
image/png.deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- class litestar.handlers.put#
Bases:
HTTPRouteHandlerPUT Route Decorator.
Use this decorator to decorate an HTTP handler for PUT requests.
- __init__(path: str | None | Sequence[str] = None, *, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, background: BackgroundTask | BackgroundTasks | None = None, before_request: BeforeRequestHookHandler | None = None, cache: bool | int | type[CACHE_FOREVER] = False, cache_control: CacheControlHeader | None = None, cache_key_builder: CacheKeyBuilder | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, etag: ETag | None = None, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, media_type: MediaType | str | None = None, middleware: Sequence[Middleware] | None = None, name: str | None = None, opt: Mapping[str, Any] | None = None, request_class: type[Request] | None = None, request_max_body_size: int | None | EmptyType = _EmptyEnum.EMPTY, response_class: type[Response] | None = None, response_cookies: ResponseCookies | None = None, response_headers: ResponseHeaders | None = None, return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, signature_namespace: Mapping[str, Any] | None = None, status_code: int | None = None, sync_to_thread: bool | None = None, content_encoding: str | None = None, content_media_type: str | None = None, deprecated: bool = False, description: str | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, operation_class: type[Operation] = <class 'litestar.openapi.spec.operation.Operation'>, operation_id: str | OperationIDCreator | None = None, raises: Sequence[type[HTTPException]] | None = None, response_description: str | None = None, responses: Mapping[int, ResponseSpec] | None = None, security: Sequence[SecurityRequirement] | None = None, summary: str | None = None, tags: Sequence[str] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, **kwargs: Any) None#
Initialize
put- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/after_request¶ – A sync or async function executed before a
Requestis passed to any route handler. If this function returns a value, the request will not reach the route handler, and instead this value will be used.after_response¶ – A sync or async function called after the response has been awaited. It receives the
Requestobject and should not return any values.background¶ – A
BackgroundTaskinstance orBackgroundTasksto execute after the response is finished. Defaults toNone.before_request¶ – A sync or async function called immediately before calling the route handler. Receives the
connection.Requestinstance and any non-Nonereturn value is used for the response, bypassing the route handler.cache¶ – Enables response caching if configured on the application level. Valid values are
Trueor a number of seconds (e.g.120) to cache the response.cache_control¶ – A
cache-controlheader of typeCacheControlHeaderthat will be added to the response.cache_key_builder¶ – A
cache-key builder function. Allows for customization of the cache key if caching is configured on the application level.dependencies¶ – A string keyed mapping of dependency
Providerinstances.dto¶ –
AbstractDTOto use for (de)serializing and validation of request data.etag¶ – An
etagheader of typeETagthat will be added to the response.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
http_method¶ – An
http method string, a member of the enumHttpMethodor a list of these that correlates to the methods the route handler function should handle.media_type¶ – A member of the
MediaTypeenum or a string with a valid IANA Media-Type.middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.request_class¶ – A custom subclass of
Requestto be used as route handler’s default request.request_max_body_size¶ – Maximum allowed size of the request body in bytes. If this size is exceeded, a ‘413 - Request Entity Too Large’ error response is returned.
response_class¶ – A custom subclass of
Responseto be used as route handler’s default response.response_headers¶ – A string keyed mapping of
ResponseHeaderinstances.responses¶ – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema
return_dto¶ –
AbstractDTOto use for serializing outbound response data.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
status_code¶ – An http status code for the response. Defaults to
200for mixed method orGET,PUTandPATCH,201forPOSTand204forDELETE.sync_to_thread¶ – A boolean dictating whether the handler function will be executed in a worker thread or the main event loop. This has an effect only for sync handler functions. See using sync handler functions.
content_encoding¶ – A string describing the encoding of the content, e.g.
base64.content_media_type¶ – A string designating the media-type of the content, e.g.
image/png.deprecated¶ – A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema.
description¶ – Text used for the route’s schema description section.
include_in_schema¶ – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.
operation_class¶ –
Operationto be used with the route’s OpenAPI schema.operation_id¶ – Either a string or a callable returning a string. An identifier used for the route’s schema operationId.
raises¶ – A list of exception classes extending from litestar.HttpException that is used for the OpenAPI documentation. This list should describe all exceptions raised within the route handler’s function/method. The Litestar ValidationException will be added automatically for the schema if any validation is involved.
response_description¶ – Text used for the route’s response schema description section.
security¶ – A sequence of dictionaries that contain information about which security scheme can be used on the endpoint.
summary¶ – Text used for the route’s schema summary section.
tags¶ – A sequence of string tags that will be appended to the OpenAPI schema.
type_decoders¶ – A sequence of tuples, each composed of a predicate testing for type identity and a msgspec hook for deserialization.
type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.
- litestar.handlers.route#
alias of
HTTPRouteHandler
- async litestar.handlers.send_websocket_stream(socket: WebSocket, stream: AsyncGenerator[Any, Any], *, close: bool = True, mode: WebSocketMode = 'text', send_handler: Callable[[WebSocket, Any], Awaitable[Any]] | None = None, listen_for_disconnect: bool = False, warn_on_data_discard: bool = True) None#
Stream data to the
socketfrom an asynchronous generator.Example
Sending the current time to the connected client every 0.5 seconds:
async def stream_current_time() -> AsyncGenerator[str, None]: while True: yield str(time.time()) await asyncio.sleep(0.5) @websocket("/time") async def time_handler(socket: WebSocket) -> None: await socket.accept() await send_websocket_stream( socket, stream_current_time(), listen_for_disconnect=True, )
- Parameters:
stream¶ – An asynchronous generator yielding data to send
close¶ – If
True, close the socket after the generator is exhaustedmode¶ – WebSocket mode to use for sending when no
send_handleris specifiedsend_handler¶ – Callable to handle the send process. If
None, defaults totype(socket).send_datalisten_for_disconnect¶ – If
True, listen for client disconnects in the background. If a client disconnects, stop the generator and cancel sending data. Should always beTrueunless disconnects are handled elsewhere, for example by reading data from the socket concurrently. Should never be set toTruewhen reading data from socket concurrently, as it can lead to data losswarn_on_data_discard¶ – If
Trueandlisten_for_disconnect=True, warn if during listening for client disconnects, data is received from the socket
- litestar.handlers.websocket#
alias of
WebsocketRouteHandler
- litestar.handlers.websocket_listener#
alias of
WebsocketListenerRouteHandler
- litestar.handlers.websocket_stream(path: str | list[str] | None = None, *, dependencies: Dependencies | None = None, exception_handlers: dict[int | type[Exception], ExceptionHandler] | None = None, guards: list[Guard] | None = None, middleware: list[Middleware] | None = None, name: str | None = None, opt: dict[str, Any] | None = None, signature_namespace: Mapping[str, Any] | None = None, websocket_class: type[WebSocket] | None = None, mode: WebSocketMode = 'text', return_dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, type_encoders: TypeEncodersMap | None = None, listen_for_disconnect: bool = True, warn_on_data_discard: bool = True, **kwargs: Any) Callable[[Callable[..., AsyncGenerator[Any, Any]]], WebsocketRouteHandler]#
Create a WebSocket handler that accepts a connection and sends data to it from an async generator.
Example
Sending the current time to the connected client every 0.5 seconds:
@websocket_stream("/time") async def send_time() -> AsyncGenerator[str, None]: while True: yield str(time.time()) await asyncio.sleep(0.5)
- Parameters:
path¶ – A path fragment for the route handler function or a sequence of path fragments. If not given defaults to
/dependencies¶ – A string keyed mapping of dependency
Providerinstances.exception_handlers¶ – A mapping of status codes and/or exception types to handler functions.
middleware¶ – A sequence of
Middleware.name¶ – A string identifying the route handler.
opt¶ – A string keyed mapping of arbitrary values that can be accessed in
Guardsor wherever you have access toRequestorASGI Scope.signature_namespace¶ – A mapping of names to types for use in forward reference resolution during signature modelling.
websocket_class¶ – A custom subclass of
WebSocketto be used as route handler’s default websocket class.mode¶ – WebSocket mode used for sending
return_dto¶ –
AbstractDTOto use for serializing outbound response data.type_encoders¶ – A mapping of types to callables that transform them into types supported for serialization.
listen_for_disconnect¶ – If
True, listen for client disconnects in the background. If a client disconnects, stop the generator and cancel sending data. Should always beTrueunless disconnects are handled elsewhere, for example by reading data from the socket concurrently. Should never be set toTruewhen reading data from socket concurrently, as it can lead to data losswarn_on_data_discard¶ – If
Trueandlisten_for_disconnect=True, warn if during listening for client disconnects, data is received from the socket**kwargs¶ – Any additional kwarg - will be set in the opt dictionary.