handlers#

class litestar.handlers.ASGIRouteHandler#

Bases: BaseRouteHandler

ASGI 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, **kwargs: Any) None#

Initialize ASGIRouteHandler.

Parameters:
  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • name – A string identifying the route handler.

  • opt – A string key mapping of arbitrary values that can be accessed in Guards or wherever you have access to Request or ASGI 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.

  • **kwargs – Any additional kwarg - will be set in the opt dictionary.

class litestar.handlers.BaseRouteHandler#

Bases: object

Base route handler.

Serves as a subclass for all route handlers

__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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • 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 Guards or wherever you have access to Request or ASGI Scope.

  • return_dtoAbstractDTO to 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 modeling. 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.

__call__(fn: AsyncAnyCallable) Self#

Replace a function with itself.

property handler_id: str#

A unique identifier used for generation of DTOs.

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 signature_model: type[litestar._signature.model.SignatureModel]#

Get the signature model for the route handler.

Returns:

A signature model for the route handler.

property fn: AsyncAnyCallable#

Get the handler function.

Raises:

ImproperlyConfiguredException – if handler fn is not set.

Returns:

Handler function

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

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 dependency_name_set: set[str]#

Set of all dependency names provided in the handler’s ownership layers.

property ownership_layers: list[Self | Controller | Router]#

Return the handler layers from the app down to the route handler.

app -> ... -> route handler

resolve_type_encoders() Mapping[Any, Callable[[Any], Any]]#

Return a merged type_encoders mapping.

This method is memoized so the computation occurs only once.

Returns:

A dict of type encoders

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

resolve_layered_parameters() dict[str, litestar.typing.FieldDefinition]#

Return all parameters declared above the handler.

resolve_guards() list[Guard]#

Return all guards in the handlers scope, starting from highest to current layer.

resolve_dependencies() dict[str, litestar.di.Provide]#

Return all dependencies correlating to handler function’s kwargs that exist in the handler’s scope.

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_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_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_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_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_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

async authorize_connection(connection: ASGIConnection) None#

Ensure the connection is authorized by running all the route guards in scope.

on_registration(app: Litestar) None#

Called once per handler when the app object is instantiated.

Parameters:

app – The Litestar app object.

Returns:

None

__str__() str#

Return a unique identifier for the route handler.

Returns:

A string

class litestar.handlers.HTTPRouteHandler#

Bases: BaseRouteHandler

HTTP Route Decorator.

Use this decorator to decorate an HTTP handler with multiple methods.

__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, 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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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.

__call__(fn: Callable[[...], Any]) HTTPRouteHandler#

Replace a function with itself.

resolve_request_class() type[litestar.connection.request.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 Request class for the route handler.

resolve_response_class() type[litestar.response.base.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 Response class for the route handler.

resolve_response_headers() frozenset[litestar.datastructures.response_header.ResponseHeader]#

Return all header parameters in the scope of the handler function.

Returns:

A dictionary mapping keys to ResponseHeader instances.

resolve_response_cookies() frozenset[litestar.datastructures.cookie.Cookie]#

Return a list of Cookie instances. Filters the list to ensure each cookie key is unique.

Returns:

A list of Cookie instances.

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_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_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 True is returned.

Returns:

The resolved ‘include_in_schema’ property.

Return type:

bool

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:

list[SecurityRequirement]

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.

Returns:

A sorted list of unique tags.

Return type:

list[str]

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

async to_response(app: Litestar, data: Any, request: Request) ASGIApp#

Return a Response from the handler by resolving and calling it.

Parameters:
  • app – The Litestar app instance

  • data – Either an instance of a Response, a Response instance or an arbitrary value.

  • request – A Request instance

Returns:

A Response instance

on_registration(app: Litestar) None#

Called once per handler when the app object is instantiated.

Parameters:

app – The Litestar app object.

Returns:

None

class litestar.handlers.WebsocketListener#

Bases: ABC

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 /

dependencies: Dependencies | None = None#

A string keyed mapping of dependency Provider instances.

dto: type[AbstractDTO] | None | EmptyType = 0#

AbstractDTO to 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.

guards: list[Guard] | None = None#

A sequence of Guard callables.

middleware: list[Middleware] | None = None#

A sequence of Middleware.

on_accept: AnyCallable | None = None#

Called after a WebSocket connection has been accepted. Can receive any dependencies

on_disconnect: AnyCallable | None = None#

Called after a WebSocket connection has been disconnected. Can receive any dependencies

receive_mode: WebSocketMode = 'text'#

WebSocket mode to receive data in, either text or binary.

send_mode: WebSocketMode = 'text'#

Websocket mode to send data in, either text or binary.

name: str | None = None#

A string identifying the route handler.

opt: dict[str, Any] | None = None#

A string keyed mapping of arbitrary values that can be accessed in Guards or wherever you have access to Request or ASGI Scope.

return_dto: type[AbstractDTO] | None | EmptyType = 0#

AbstractDTO to use for serializing outbound response data.

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_decoders

type_encoders: TypeEncodersMap | None = None#

A mapping of types to callables that transform them into types supported for serialization.

Type:

type_encoders

websocket_class: type[WebSocket] | None = None#

A custom subclass of WebSocket to be used as route handler’s default websocket class.

Type:

websocket_class

__init__(owner: Router) None#

Initialize a WebsocketListener instance.

Parameters:

owner – The Router instance that owns this listener.

abstract on_receive(*args: Any, **kwargs: Any) Any#

Called after data has been received from the WebSocket.

This should take a data argument, receiving the processed WebSocket data, and can additionally include handler dependencies such as state, or other regular dependencies.

Data returned from this function will be serialized and sent via the socket according to handler configuration.

class litestar.handlers.WebsocketRouteHandler#

Bases: BaseRouteHandler

Websocket 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 Provider instances.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • 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 Guards or wherever you have access to Request or ASGI 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.

  • **kwargs – Any additional kwarg - will be set in the opt dictionary.

  • websocket_class – A custom subclass of WebSocket to be used as route handler’s default websocket class.

resolve_websocket_class() type[litestar.connection.websocket.WebSocket]#

Return the closest custom WebSocket class in the owner graph or the default Websocket class.

This method is memoized so the computation occurs only once.

Returns:

The default WebSocket class for the route handler.

class litestar.handlers.WebsocketListenerRouteHandler#

Bases: WebsocketRouteHandler

A websocket listener that automatically accepts a connection, handles disconnects, invokes a callback function every time new data is received and sends any data returned

__init__(path: str | list[str] | None = None, *, connection_lifespan: Callable[[...], AbstractAsyncContextManager[Any]] | None = None, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = 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, opt: dict[str, Any] | None = None, return_dto: type[AbstractDTO] | None | EmptyType = Empty, signature_namespace: Mapping[str, Any] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[litestar.connection.websocket.WebSocket] | None = None, **kwargs: Any) None#
__init__(path: str | list[str] | None = None, *, connection_accept_handler: Callable[[WebSocket], Coroutine[Any, Any, None]] = WebSocket.accept, dependencies: Dependencies | None = None, dto: type[AbstractDTO] | None | EmptyType = 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: Callable[[...], Any] | None = None, on_disconnect: Callable[[...], Any] | None = None, opt: dict[str, Any] | None = None, return_dto: type[AbstractDTO] | None | EmptyType = Empty, signature_namespace: Mapping[str, Any] | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[litestar.connection.websocket.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 WebSocket instance and returns a coroutine that when awaited, will accept the connection. Defaults to WebSocket.accept.

  • connection_lifespan – An asynchronous context manager, handling the lifespan of the connection. By default, it calls the connection_accept_handler, on_connect and on_disconnect. Can request any dependencies, for example the WebSocket connection

  • dependencies – A string keyed mapping of dependency Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • 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 WebSocket connection

  • on_disconnect – Callback invoked after a connection has been closed. Can request any dependencies, for example the WebSocket connection

  • opt – A string keyed mapping of arbitrary values that can be accessed in Guards or wherever you have access to Request or ASGI Scope.

  • return_dtoAbstractDTO to 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 WebSocket to be used as route handler’s default websocket class.

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

property signature_model: type[litestar._signature.model.SignatureModel]#

Get the signature model for the route handler.

Returns:

A signature model for the route handler.

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:
  • socket – The WebSocket connection

  • on_accept_dependencies – Dependencies requested by the on_accept hook

  • on_disconnect_dependencies – Dependencies requested by the on_disconnect hook

By, default this will

weboscket_class#

WebSocket class

litestar.handlers.asgi#

alias of ASGIRouteHandler

class litestar.handlers.delete#

Bases: HTTPRouteHandler

DELETE 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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the connection.Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • dependencies – A string keyed mapping of dependency Provider instances.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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: HTTPRouteHandler

GET 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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the connection.Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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: HTTPRouteHandler

HEAD 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

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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the connection.Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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: HTTPRouteHandler

PATCH 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, 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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the connection.Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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: HTTPRouteHandler

POST 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, 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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the connection.Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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: HTTPRouteHandler

PUT 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, 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 Request is 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 Request object and should not return any values.

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • before_request – A sync or async function called immediately before calling the route handler. Receives the connection.Request instance and any non-None return value is used for the response, bypassing the route handler.

  • cache – Enables response caching if configured on the application level. Valid values are True or a number of seconds (e.g. 120) to cache the response.

  • cache_control – A cache-control header of type CacheControlHeader that 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 Provider instances.

  • dtoAbstractDTO to use for (de)serializing and validation of request data.

  • etag – An etag header of type ETag that will be added to the response.

  • exception_handlers – A mapping of status codes and/or exception types to handler functions.

  • guards – A sequence of Guard callables.

  • http_method – An http method string, a member of the enum HttpMethod or a list of these that correlates to the methods the route handler function should handle.

  • media_type – A member of the MediaType enum 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 Guards or wherever you have access to Request or ASGI Scope.

  • request_class – A custom subclass of Request to be used as route handler’s default request.

  • response_class – A custom subclass of Response to be used as route handler’s default response.

  • response_cookies – A sequence of Cookie instances.

  • response_headers – A string keyed mapping of ResponseHeader instances.

  • responses – A mapping of additional status codes and a description of their expected content. This information will be included in the OpenAPI schema

  • return_dtoAbstractDTO to 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 200 for mixed method or GET, PUT and PATCH, 201 for POST and 204 for DELETE.

  • 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_classOperation to 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

litestar.handlers.websocket#

alias of WebsocketRouteHandler

litestar.handlers.websocket_listener#

alias of WebsocketListenerRouteHandler