app#

class litestar.app.HandlerIndex#

Bases: TypedDict

Map route handler names to a mapping of paths + route handler.

It’s returned from the ‘get_handler_index_by_name’ utility method.

paths: list[str]#

Full route paths to the route handler.

handler: RouteHandlerType#

Route handler instance.

identifier: str#

Unique identifier of the handler.

Either equal to :attr`__name__ <obj.__name__>` attribute or __str__ value of the handler.

class litestar.app.Litestar#

Bases: Router

The Litestar application.

Litestar is the root level of the app - it has the base path of / and all root level Controllers, Routers and Route Handlers should be registered on it.

__init__(route_handlers: Sequence[ControllerRouterHandler] | None = None, *, after_exception: Sequence[AfterExceptionHookHandler] | None = None, after_request: AfterRequestHookHandler | None = None, after_response: AfterResponseHookHandler | None = None, allowed_hosts: Sequence[str] | AllowedHostsConfig | None = None, before_request: BeforeRequestHookHandler | None = None, before_send: Sequence[BeforeMessageSendHookHandler] | None = None, cache_control: CacheControlHeader | None = None, compression_config: CompressionConfig | None = None, cors_config: CORSConfig | None = None, csrf_config: CSRFConfig | None = None, dto: type[AbstractDTO] | None | EmptyType = _EmptyEnum.EMPTY, debug: bool | None = None, dependencies: Dependencies | None = None, etag: ETag | None = None, event_emitter_backend: type[BaseEventEmitterBackend] = <class 'litestar.events.emitter.SimpleEventEmitter'>, exception_handlers: ExceptionHandlersMap | None = None, guards: Sequence[Guard] | None = None, include_in_schema: bool | EmptyType = _EmptyEnum.EMPTY, listeners: Sequence[EventListener] | None = None, logging_config: BaseLoggingConfig | EmptyType | None = _EmptyEnum.EMPTY, middleware: Sequence[Middleware] | None = None, multipart_form_part_limit: int = 1000, on_app_init: Sequence[OnAppInitHandler] | None = None, on_shutdown: Sequence[LifespanHook] | None = None, on_startup: Sequence[LifespanHook] | None = None, openapi_config: OpenAPIConfig | None = OpenAPIConfig(title='Litestar API', version='1.0.0', create_examples=False, random_seed=10, contact=None, description=None, external_docs=None, license=None, security=None, components=Components(schemas={}, responses=None, parameters=None, examples=None, request_bodies=None, headers=None, security_schemes=None, links=None, callbacks=None, path_items=None), servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, operation_id_creator=<function default_operation_id_creator>, path=None, render_plugins=[<litestar.openapi.plugins.SwaggerRenderPlugin object>, <litestar.openapi.plugins.RapidocRenderPlugin object>, <litestar.openapi.plugins.RedocRenderPlugin object>, <litestar.openapi.plugins.JsonRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.StoplightRenderPlugin object>], openapi_router=None, openapi_controller=None, root_schema_site='redoc', enabled_endpoints={'swagger', 'rapidoc', 'redoc', 'openapi.json', 'openapi.yml', 'openapi.yaml', 'oauth2-redirect.html', 'elements'}), opt: Mapping[str, Any] | None = None, parameters: ParametersMap | None = None, path: str | None = None, plugins: Sequence[PluginProtocol] | None = None, request_class: type[Request] | None = None, response_cache_config: ResponseCacheConfig | 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, security: Sequence[SecurityRequirement] | None = None, signature_namespace: Mapping[str, Any] | None = None, signature_types: Sequence[Any] | None = None, state: State | None = None, static_files_config: Sequence[StaticFilesConfig] | None = None, stores: StoreRegistry | dict[str, Store] | None = None, tags: Sequence[str] | None = None, template_config: TemplateConfigType | None = None, type_decoders: TypeDecodersSequence | None = None, type_encoders: TypeEncodersMap | None = None, websocket_class: type[WebSocket] | None = None, lifespan: Sequence[Callable[[Litestar], AbstractAsyncContextManager] | AbstractAsyncContextManager] | None = None, pdb_on_exception: bool | None = None, experimental_features: Iterable[ExperimentalFeatures] | None = None) None#

Initialize a Litestar application.

Parameters:
  • after_exception – A sequence of exception hook handlers. This hook is called after an exception occurs. In difference to exception handlers, it is not meant to return a response - only to process the exception (e.g. log it, send it to Sentry etc.).

  • after_request – A sync or async function executed after the route handler function returned and the response object has been resolved. Receives the response object.

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

  • allowed_hosts – A sequence of allowed hosts, or an AllowedHostsConfig instance. Enables the builtin allowed hosts middleware.

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

  • before_send – A sequence of before send hook handlers. Called when the ASGI send function is called.

  • cache_control – A cache-control header of type CacheControlHeader to add to route handlers of this app. Can be overridden by route handlers.

  • compression_config – Configures compression behaviour of the application, this enabled a builtin or user defined Compression middleware.

  • cors_config – If set, configures CORS handling for the application.

  • csrf_config – If set, configures CSRFMiddleware.

  • debug – If True, app errors rendered as HTML with a stack trace.

  • dependencies – A string keyed mapping of dependency Providers.

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

  • etag – An etag header of type ETag to add to route handlers of this app. Can be overridden by route handlers.

  • event_emitter_backend – A subclass of BaseEventEmitterBackend.

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

  • guards – A sequence of Guard callables.

  • include_in_schema – A boolean flag dictating whether the route handler should be documented in the OpenAPI schema.

  • lifespan – A list of callables returning async context managers, wrapping the lifespan of the ASGI application

  • listeners – A sequence of EventListener.

  • logging_config – A subclass of BaseLoggingConfig.

  • middleware – A sequence of Middleware.

  • multipart_form_part_limit – The maximal number of allowed parts in a multipart/formdata request. This limit is intended to protect from DoS attacks.

  • on_app_init – A sequence of OnAppInitHandler instances. Handlers receive an instance of AppConfig that will have been initially populated with the parameters passed to Litestar, and must return an instance of same. If more than one handler is registered they are called in the order they are provided.

  • on_shutdown – A sequence of LifespanHook called during application shutdown.

  • on_startup – A sequence of LifespanHook called during application startup.

  • openapi_config – Defaults to DEFAULT_OPENAPI_CONFIG

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

  • parameters – A mapping of Parameter definitions available to all application paths.

  • path

    A path fragment that is prefixed to all route handlers, controllers and routers associated with the application instance.

    New in version 2.8.0.

  • pdb_on_exception – Drop into the PDB when an exception occurs.

  • plugins – Sequence of plugins.

  • request_class – An optional subclass of Request to use for http connections.

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

  • response_cookies – A sequence of Cookie.

  • response_headers – A string keyed mapping of ResponseHeader

  • response_cache_config – Configures caching behavior of the application.

  • return_dtoAbstractDTO to use for serializing outbound response data.

  • route_handlers – A sequence of route handlers, which can include instances of Router, subclasses of Controller or any callable decorated by the route handler decorators.

  • security – A sequence of dicts that will be added to the schema of all route handlers in the application. See SecurityRequirement for details.

  • signature_namespace – A mapping of names to types for use in forward reference resolution during signature modeling.

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

  • state – An optional State for application state.

  • static_files_config – A sequence of StaticFilesConfig

  • stores – Central registry of Store that will be available throughout the application. If this is a dictionary to it will be passed to a StoreRegistry. If it is a StoreRegistry, this instance will be used directly.

  • tags – A sequence of string tags that will be appended to the schema of all route handlers under the application.

  • template_config – An instance of TemplateConfig

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

  • websocket_class – An optional subclass of WebSocket to use for websocket connections.

  • experimental_features – An iterable of experimental features to enable

async __call__(scope: Scope | LifeSpanScope, receive: Receive | LifeSpanReceive, send: Send | LifeSpanSend) None#

Application entry point.

Lifespan events (startup / shutdown) are sent to the lifespan handler, otherwise the ASGI handler is used

Parameters:
  • scope – The ASGI connection scope.

  • receive – The ASGI receive function.

  • send – The ASGI send function.

Returns:

None

lifespan() AsyncGenerator[None, None]#

Context manager handling the ASGI lifespan.

It will be entered when the lifespan message has been received from the server, and exit after the asgi.shutdown message. During this period, it is responsible for calling the on_startup, on_shutdown hooks, as well as custom lifespan managers.

property openapi_schema: OpenAPI#

Access the OpenAPI schema of the application.

Returns:

The OpenAPI <pydantic_openapi_schema.open_api.OpenAPI> instance of the application.

Raises:

ImproperlyConfiguredException – If the application openapi_config attribute is None.

classmethod from_config(config: AppConfig) Self#

Initialize a Litestar application from a configuration instance.

Parameters:

config – An instance of AppConfig <.config.AppConfig>

Returns:

An instance of Litestar application.

register(value: ControllerRouterHandler) None#

Register a route handler on the app.

This method can be used to dynamically add endpoints to an application.

Parameters:

value – An instance of Router, a subclass of Controller or any function decorated by the route handler decorators.

Returns:

None

get_handler_index_by_name(name: str) HandlerIndex | None#

Receives a route handler name and returns an optional dictionary containing the route handler instance and list of paths sorted lexically.

Examples

from litestar import Litestar, get


@get("/", name="my-handler")
def handler() -> None:
    pass


app = Litestar(route_handlers=[handler])

handler_index = app.get_handler_index_by_name("my-handler")

# { "paths": ["/"], "handler" ... }
Parameters:

name – A route handler unique name.

Returns:

A HandlerIndex instance or None.

route_reverse(name: str, **path_parameters: Any) str#

Receives a route handler name, path parameter values and returns url path to the handler with filled path parameters.

Examples

from litestar import Litestar, get


@get("/group/{group_id:int}/user/{user_id:int}", name="get_membership_details")
def get_membership_details(group_id: int, user_id: int) -> None:
    pass


app = Litestar(route_handlers=[get_membership_details])

path = app.route_reverse("get_membership_details", user_id=100, group_id=10)

# /group/10/user/100
Parameters:
  • name – A route handler unique name.

  • **path_parameters – Actual values for path parameters in the route.

Raises:

NoRouteMatchFoundException – If route with ‘name’ does not exist, path parameters are missing in **path_parameters or have wrong type.

Returns:

A fully formatted url path.

url_for_static_asset(name: str, file_path: str) str#

Receives a static files handler name, an asset file path and returns resolved url path to the asset.

Examples

from litestar import Litestar
from litestar.static_files.config import StaticFilesConfig

app = Litestar(
    static_files_config=[
        StaticFilesConfig(directories=["css"], path="/static/css", name="css")
    ]
)

path = app.url_for_static_asset("css", "main.css")

# /static/css/main.css
Parameters:
  • name – A static handler unique name.

  • file_path – a string containing path to an asset.

Raises:

NoRouteMatchFoundException – If static files handler with name does not exist.

Returns:

A url path to the asset.

property route_handler_method_view: dict[str, list[str]]#

Map route handlers to paths.

Returns:

A dictionary of router handlers and lists of paths as strings

update_openapi_schema() None#

Update the OpenAPI schema to reflect the route handlers registered on the app.

Returns:

None

emit(event_id: str, *args: Any, **kwargs: Any) None#

Emit an event to all attached listeners.

Parameters:
  • event_id – The ID of the event to emit, e.g my_event.

  • args – args to pass to the listener(s).

  • kwargs – kwargs to pass to the listener(s)

Returns:

None

litestar.app.DEFAULT_OPENAPI_CONFIG = OpenAPIConfig(title='Litestar API', version='1.0.0', create_examples=False, random_seed=10, contact=None, description=None, external_docs=None, license=None, security=None, components=Components(schemas={}, responses=None, parameters=None, examples=None, request_bodies=None, headers=None, security_schemes=None, links=None, callbacks=None, path_items=None), servers=[Server(url='/', description=None, variables=None)], summary=None, tags=None, terms_of_service=None, use_handler_docstrings=False, webhooks=None, operation_id_creator=<function default_operation_id_creator>, path=None, render_plugins=[<litestar.openapi.plugins.SwaggerRenderPlugin object>, <litestar.openapi.plugins.RapidocRenderPlugin object>, <litestar.openapi.plugins.RedocRenderPlugin object>, <litestar.openapi.plugins.JsonRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.YamlRenderPlugin object>, <litestar.openapi.plugins.StoplightRenderPlugin object>], openapi_router=None, openapi_controller=None, root_schema_site='redoc', enabled_endpoints={'swagger', 'rapidoc', 'redoc', 'openapi.json', 'openapi.yml', 'openapi.yaml', 'oauth2-redirect.html', 'elements'})#

The default OpenAPI config used if not configuration is explicitly passed to the Litestar instance constructor.