Litestar 2 Changelog#
2.18.0#
Released: 2025-10-05Features#
- Deprecate 
litestar.plugins.sqlalchemymodule# Deprecate the
litestar.plugins.sqlalchemymodule, which is scheduled for removal in v3.0.This deprecation follows the migration to advanced-alchemy. Users should update their imports:
# Old (deprecated) # New
References: litestar-org/litestar#4343
- Add 
round_tripparameter toPydanticPlugin# Add new
round_tripparameter toPydanticPlugin, allowing correct serialization of types likepydanctic.Json.References: litestar-org/litestar#4349, litestar-org/litestar#4350
Bugfixes#
- Fix header spoofing vulnerability in 
RateLimitMiddlewarethat allowed bypassing client-specific rate limits# Fix a vulnerability in
RateLimitMiddlewarethat allowed clients to bypass the limit by spoofing theX-FORWARDED-FORheader.Who is affected?
All usages of the
RateLimitMiddlewarethat did not customizeRateLimitMiddleware.cache_key_from_request.What needs to be done?
The middleware has been fixed to remove this particular vulnerability, by ignoring the
X-FORWARDED-FORheader when determining a client’s identity. If you are usinglitestar>=2.18.0, nothing needs to be done.Note
Applications operating behind a proxy should consult Using behind a proxy on how to obtain reliable client identification in such cases.
References:
- OpenAPI: Fix broken Typescript export for 
NotRequired# Fix a bug that would result in broken Typescript type definition for a model using
NotRequiredReferences: litestar-org/litestar#4198, litestar-org/litestar#4318
- CLI: Fix command registration#
 Fix an issue where CLI plugins no longer appear in the command help text after recent updates to
rich-clickandclick.Ensure plugins load before rendering the help text so they appear in the formatted help output.
References: litestar-org/litestar#4298
- Remove fix polyfactory deprecation warning#
 Fix a deprecation warning from polyfactory caused by a changed default value.
References: litestar-org/litestar#4292
- Ensure 
MethodNotAllowedExceptionproperly setsAllowheader during routing# Ensure
MethodNotAllowedExceptionexceptions raised during routing always includes anAllowheader.References: litestar-org/litestar#4277, litestar-org/litestar#4289
- Preserve empty strings in 
multipart/form-datarequests# Preserve empty strings in multipart forms instead of converting them to
None.References: litestar-org/litestar#4204, litestar-org/litestar#4271
- OpenAPI: Regression - Fix missing constraints for 
msgspec.Struct# Ensure constraints on set on an
msgspec.Structare always reflected in the OpenAPI schema, for simple (non-union, non-optional, non-nested) fields.References: litestar-org/litestar#3999, litestar-org/litestar#4282
- Fix 
KeyErrorwhen usingdatakeyword argument in dependency function# Fix a
KeyErrorthat occured when a dependency function used thedatakeyword argument, if nodatakeyword argument was used in the handler requesting this dependency.References: litestar-org/litestar#4230, litestar-org/litestar#4270
- OpenAPI - Regression: Allow 
Parameterto set an Enum’s schema fields# Fix a bug introduced in
2.14.0that would prevent an Enum field’s OpenAPI schema to be modified viaParameter().References: litestar-org/litestar#4250, litestar-org/litestar#4251
- CLI: Fix 
TypeErrorwhen passing--helpand –app-dir` simultaneously# Fix a bug that would raise a
TypeErrorwhen the CLI’s--helpoption was invoked, if the--app-diroption was also set.References: litestar-org/litestar#4331, litestar-org/litestar#4341
- CLI: Fix 
--app-dirbeing ignore on subsequent reloads when used together with--reloadoption# Fix a bug that would cause the
--app-diroption to be ignored after the first reload, because it was not passed properly to uvicorn.References: litestar-org/litestar#4329, litestar-org/litestar#4352
- OpenAPI: Use 
NotRequiredinstead ofOptionalfor values with adefault_factory# Fix a bug that would consider fields with a
default_factoryset to beOptionalinstead ofNotRequired.References: litestar-org/litestar#4294, litestar-org/litestar#4347
- Fix 
Streamresponse being treated asFileresponse in OpenAPI schema# Prevent handlers returning a
Streamfrom falsely indicating a file response in the OpenAPI schema with file-specific headers such ascontent-length,last-modified, andetag.References: litestar-org/litestar#4371
2.17.0#
Released: 2025-08-09Features#
- OpenAPI: Add option to exclude parameter from schema#
 Add a new
exclude_from_schemaparameter toParameter()that allows to exclude a specific parameter from the OpenAPI schema.References: litestar-org/litestar#4177
- OpenAPI: Extend support for Pydantic’s custom date(time) types#
 Add full OpenAPI schema support for Pydantic’s custom date(time) types:
PastDateFutureDatePastDatetimeFutureDatetimeAwareDatetimeNaiveDatetime
References: litestar-org/litestar#4217, litestar-org/litestar#4218
- Make 
ReceiveRoutePluginpublic# Make the previously internally used
litestar.plugins.ReceiveRoutePluginpublic.References: litestar-org/litestar#4220
Bugfixes#
- Fix CRLF injection vulnerability in exception logging#
 Fix a CRLF vulnerability in the exception logging where Litestar included the raw request path in the logged exception, allowing potential attackers to inject newlines into the log message.
References:
- OpenAPI: Fix empty response body when using DTO and 
Response[T]annotation# Fix a bug that result in an empty response body in the OpenAPI schema when a
return_dtowas defined on a handler with a genericResponseannotation, such as@get("/get_items", return_dto=ItemReadDTO) async def get_items() -> Response[list[Item]]: return Response( content=[ Item(id=1, name="Item 1", secret="123"), ], )
References: litestar-org/litestar#3888, litestar-org/litestar#4158
- OpenAPI: Ensure deterministic order of schema types#
 Fix a bug that would result in a non-deterministic ordering of
Literal/ Enum type unions, such asLiteral[*] | NoneReferences: litestar-org/litestar#3646, litestar-org/litestar#4239
- Ensure dependency cleanup of 
yielddependency happens in reverse order# Fix a regression in the DI system that would cause generator dependencies to be cleaned up in the order they were entered, instead of the reverse order.
References: litestar-org/litestar#4246
2.16.0#
Released: 2025-05-04Features#
- Logging: Selectively disable logging for status codes or exception types#
 Add support for disabling stack traces for specific status codes or exception types when in debug mode or running with
log_exceptions="always"Disable tracebacks for ‘404 - Not Found’ exceptions#from litestar import Litestar from litestar.logging import LoggingConfig app = Litestar( route_handlers=[index, value_error, name_error], logging_config=LoggingConfig( disable_stack_trace={404}, log_exceptions="always", ), )
References: litestar-org/litestar#4081, litestar-org/litestar#4086
- Reference route handler in error message for return value / status code mismatch#
 Improve error message of
ImproperlyConfiguredExceptionraised when a route handler’s return value annotation is incompatible with its status code.References: litestar-org/litestar#4157
- DTO: Improve inspection and tracebacks for generated functions#
 Generated transfer functions now populate
linecacheto improve tracebacks and support introspection of the generated functions e.g. viainspect.getsource()Before:
File "<string>", line 18, in func TypeError: <something's wrong>
After:
File "dto_transfer_function_0971e01f653c", line 18, in func TypeError: <something's wrong>
References: litestar-org/litestar#4159
- DTO: Add custom attribute accessor callable#
 Add
attribute_accessorproperty toAbstractDTO, that can be set to a customgetattr()-like function which will be used every time an attribute is accessed on a source instanceReferences: litestar-org/litestar#4160
- OpenAPI: Add custom example ids support#
 Add a new field
idtoExample, to set a custom ID for examplesReferences: litestar-org/litestar#4013, litestar-org/litestar#4133
- OpenAPI: Allow passing scalar configuration options#
 Add an
optionsparameter toScalarRenderPlugin, that can be used to pass options directly to scalar.from litestar import Litestar from litestar.openapi.config import OpenAPIConfig from litestar.openapi.plugins import ScalarRenderPlugin scalar_plugin = ScalarRenderPlugin(version="1.19.5", options={"showSidebar": False}) app = Litestar( route_handlers=[hello_world], openapi_config=OpenAPIConfig( title="Litestar Example", description="Example of Litestar with Scalar OpenAPI docs", version="0.0.1", render_plugins=[scalar_plugin], path="/docs", ), )
References: litestar-org/litestar#3951, litestar-org/litestar#4162
Bugfixes#
- Typing: remove usage of private 
_AnnotatedAlias# Remove deprecated usage of
_AnnotatedAlias, which is no longer needed for backwards compatibility.References: litestar-org/litestar#4126
- DI: Ensure generator dependencies always handle error during clean up#
 Fix issue where dependency cleanup could be skipped during exception handling, if another exception happened during the cleanup itself.
Ensure all dependencies are cleaned up, even if exceptions occur.
Group exceptions using
ExceptionGroupduring cleanup phase.
References: litestar-org/litestar#4148
- CLI: Improve error message on 
ImportError# Fix misleading error message when using
--appCLI argument and an unrelatedImportErroroccurs. Unrelated import errors will now propagate as usualReferences: litestar-org/litestar#4129, litestar-org/litestar#4152
- CLI: Ensure dynamically added commands / groups are always visible#
 Fix an issue where dynamically added commands or groups were not always visible during listing e.g. via
--helpReferences: litestar-org/litestar#2783, litestar-org/litestar#4161
- Testing: Ensure subprocess client does not swallow startup failure#
 Ensure
StartupErroris raised bysubprocess_sync_client()andsubprocess_async_client()if the application failed to start within the timeout.References: litestar-org/litestar#4021, litestar-org/litestar#4153
- OpenAPI: Use 
prefixItemsfor fixed-length tuples# Use
prefixItemsinstead ofarraysyntax to render fixed-length tuplesReferences: litestar-org/litestar#4130, litestar-org/litestar#4132
2.15.2#
Released: 2025-04-06Bugfixes#
- Events: Fix error handling for synchronous handlers#
 Fix a bug where exceptions weren’t handled correctly on synchronous event handlers, and would result in another exception.
@listener("raise_exception") def raise_exception_if_odd(value) -> None: if value is not None and value % 2 != 0: raise ValueError(f"{value} is odd")
Would raise an
AttributeError: 'AsyncCallable' object has no attribute '__name__'. Did you mean: '__ne__'?References: litestar-org/litestar#4045
- Fix wrong order of arguments in FileSystemAdapter passed to 
openfsspec file system# The order of arguments of various fsspec implementations varies, causing
FileSystemAdapter.opento fail in different ways. This was fixed by always passing arguments as keywords to the file system.References: litestar-org/litestar#4049
- Correctly handle 
typing_extensions.TypeAliasTypeontyping-extensions>4.13.0# Handle the diverging
TypeAliasTypeintroduced in typing-extensions4.13.0; This type is no longer backwards compatible, as it is a distinct new type fromtyping.TypeAliasTypeReferences: litestar-org/litestar#4088, litestar-org/litestar#4089
2.15.1#
Released: 2025-02-27Bugfixes#
- Warn about using streaming responses with a 
body# Issue a warning if the
bodyparameter of a streaming response is used, as setting this has no effectReferences: litestar-org/litestar#4033
- Fix incorrect deprecation warning issued when subclassing middlewares#
 Fix a bug introduced in #3996 that would incorrectly issue a deprecation warning if a user subclassed a Litestar built-in middleware which itself subclasses
AbstractMiddlewareReferences: litestar-org/litestar#4035, litestar-org/litestar#4036
2.15.0#
Released: 2025-02-26Features#
- JWT: Revoked token handler#
 Add a new
revoked_token_handleron same level asretrieve_user_handler, forBaseJWTAuth.References: litestar-org/litestar#3960
- Allow 
route_reverseparams of typeuuidto be passed asstr# Allows params of type
uuidto be passed as strings (e.g. their hex representation) intoroute_reverse()References: litestar-org/litestar#3972
- CLI: Better error message for invalid 
--appstring# Improve the error handling when an invalid
--appstring is passedReferences: litestar-org/litestar#3893, litestar-org/litestar#3977
- DTO: Support 
@propertyfields for msgspec and dataclass# Support
propertyfields for msgspec and dataclasses during serialization and for OpenAPI schema generation.References: litestar-org/litestar#3981
- Add new 
ASGIMiddleware# Add a new base middleware class to facilitate easier configuration and middleware dispatching.
The new
ASGIMiddlewarefeatures the same functionality asAbstractMiddleware, but makes it easier to pass configuration directly to middleware classes without a separate configuration object, allowing the need to useDefineMiddleware.See also
References: litestar-org/litestar#3996
- Add 
SerializationPluginandInitPluginto replace their respective protocols# Add
SerializationPluginto replaceSerializationPluginProtocolAdd
InitPluginto replaceInitPluginProtocol
Following the same approach as for other plugins, they inherit their respective protocol for now, to keep type / isinstance checks compatible.
Important
The plugin protocols will be removed in version 3.0
References: litestar-org/litestar#4025
- Allow passing a 
debugger_moduleto the application# A new
debugger_moduleparameter has been added toLitestar, which can receive any debugger module that implements apdb.post_mortem()function with the same signature as the stdlib. This function will be called when an exception occurs andpdb_on_exceptionis set toTrue.References: litestar-org/litestar#3967
Bugfixes#
- Prevent accidental 
scopekey overrides by mounted ASGI apps# When mounting ASGI apps, there’s no guarantee they won’t overwrite some key in the
scopethat we rely on, e.g.scope["app"], which is what caused litestar-org/litestar#3934.To prevent this, two thing shave been changed:
We do not store the Litestar instance under the generic
appkey anymore, but the more specificlitestar_appkey. In addition thefrom_scope()method has been added, which can be used to safely access the current app from the scopeA new parameter
copy_scopehas been added to the ASGI route handler, which, when set toTruewill copy the scope before calling into the mounted ASGI app, aiming to make things behave more as expected, by giving the called app its own environment without causing any side-effects. Since this change might break some things, It’s been left it with a default ofNone, which does not copy the scope, but will issue a warning if the mounted app modified it, enabling users to decide how to deal with that situation
References: litestar-org/litestar#3934, litestar-org/litestar#3945
- Fix deprecated 
attrsimport# A deprecated import of the
attrsplugins caused a warning. This has been fixed.References: litestar-org/litestar#3946, litestar-org/litestar#3947
2.14.0#
Released: 2025-02-12Features#
- Deprecate 
litestar.contrib.prometheusin favour oflitestar.plugins.prometheus# The module
litestar.contrib.prometheushas been moved tolitestar.plugins.prometheus.litestar.contrib.prometheuswill be deprecated in the next major versionReferences: litestar-org/litestar#3863
- Deprecate 
litestar.contrib.attrsin favour oflitestar.plugins.attrs# The module
litestar.contrib.attrshas been moved tolitestar.plugins.attrs.litestar.contrib.attrswill be deprecated in the next major versionReferences: litestar-org/litestar#3862
- Add a streaming multipart parser#
 Add a streaming multipart parser via the multipart library
This provides
Ability to stream large / larger-than-memory file uploads
Better / more correct edge case handling
Still good performance
References: litestar-org/litestar#3872
- Add WebSocket send stream#
 Add a new
websocket_stream()route handler that supports streaming data to a WebSocket via an async generator.@websocket_stream("/") async def handler() -> AsyncGenerator[str, None]: yield str(time.time()) await asyncio.sleep(.1)
This is roughly equivalent to (with some edge case handling omitted):
@websocket("/") async def handler(socket: WebSocket) -> None: await socket.accept() try: async with anyio.task_group() as tg: # 'receive' in the background to catch client disconnects tg.start_soon(socket.receive) while True: socket.send_text(str(time.time())) await asyncio.sleep(.1) finally: await socket.close()
Just like the WebSocket listeners, it also supports dependency injection and serialization:
@dataclass class Event: time: float data: str async def provide_client_info(socket: WebSocket) -> str: return f"{socket.client.host}:{socket.client.port}" @websocket_stream("/", dependencies={"client_info": provide_client_info}) async def handler(client_info: str) -> AsyncGenerator[Event, None]: yield Event(time=time.time(), data="hello, world!") await asyncio.sleep(.1)
See also
References: litestar-org/litestar#3894
- Add query params to 
Redirect# Add a
query_paramsparameter toRedirect, to supply query parameters for a redirectReferences: litestar-org/litestar#3891, litestar-org/litestar#3901
- Add Valkey as a native store#
 Add a new
ValkeyStore, which provides the same functionality as theRedisStorebut using valkey instead.The necessary dependencies can be installed with the
litestar[valkey]extra, which includesvalkeyas well aslibvalkeyas an optimisation layer.References: litestar-org/litestar#3892
- Correctly specify 
"path"as an error message source for validation errors# Use
"path"as the"source"property of a validation error message if the key is a path parameter.References: litestar-org/litestar#3919, litestar-org/litestar#3920
- Add subprocess test client#
 Add new
subprocess_async_client()andsubprocess_sync_client(), which can run an application in a new process, primarily for the purpose of end-to-end testing.The application will be run with
uvicorn, which has to be installed separately or via thelitestar[standard]group.References: litestar-org/litestar#3654, litestar-org/litestar#3655
- Support for Python 3.13#
 Support Python 3.13
Important
There are no Python 3.13 prebuilt wheels for
psycopg[binary]. If you rely on this for development, you’ll need to have the postgres development libraries installedpicologgingdoes not currently support Python 3.13
References: litestar-org/litestar#3850
Bugfixes#
- OpenAPI: Always generate refs for enums#
 Ensure that enums always generate a schema reference instead of being inlined
References: litestar-org/litestar#3518, litestar-org/litestar#3525
- Support varying 
mtimesemantics across different fsspec implementations# Change the implementation of
Fileto be able to handle most fsspec implementation’smtimeequivalent.This is necessary because fsspec implementations do not have a standardised way to retrieve an
mtimeequivalent; Some report anmtime, while some may use a different key (e.g.Last-Modified) and others do not report this value at all.References: litestar-org/litestar#3899, litestar-org/litestar#3902
- OpenAPI: Ensure query-only properties are only included in queries#
 Remove the inclusion of the query-only properties
allowEmptyValueandallowReservedin path, cookie, header parameter and response header schemasReferences: litestar-org/litestar#3908, litestar-org/litestar#3909
- Channels: Use 
SQLfunction for in psycopg backend# Update the
PsycoPgChannelsBackendbackend to use the native psycopgSQLAPIReferences: litestar-org/litestar#3916
2.13.0#
Released: 2024-11-20Features#
- Add 
request_max_body_sizelayered parameter# Add a new
request_max_body_sizelayered parameter, which limits the maximum size of a request body before returning a413 - Request Entity Too Large.See also
References:
- Send CSRF request header in OpenAPI plugins#
 Supported OpenAPI UI clients will extract the CSRF cookie value and attach it to the request headers if CSRF is enabled on the application.
References: litestar-org/litestar#3754
- deprecate litestar.contrib.sqlalchemy#
 Deprecate the
litestar.contrib.sqlalchemymodule in favor oflitestar.plugins.sqlalchemyReferences: litestar-org/litestar#3755
- implement HTMX plugin using litestar-htmx#
 This plugin migrates the HTMX integration to
litestar.plugins.htmx.This logic has been moved to it’s own repository named
litestar-htmxReferences: litestar-org/litestar#3837
- Pydantic: honor 
hide_input_in_errorsin throwing validation exceptions# Pydantic’s
BaseModelsupports configuration to hide data values when throwing exceptions, via settinghide_input_in_errors– see https://docs.pydantic.dev/2.0/api/config/#pydantic.config.ConfigDict.hide_input_in_errors and https://docs.pydantic.dev/latest/usage/model_config/#hide-input-in-errorsLitestar will now honour this setting
References: litestar-org/litestar#3843
- deprecate``litestar.contrib.pydantic``#
 ## Description
Deprecate
litestar.contrib.pydanticin favor oflitestar.plugins.pydanticReferences: litestar-org/litestar#3787, litestar-org/litestar#3852
Bugfixes#
- Fix sign bug in rate limit middelware#
 Fix a bug in the rate limit middleware, that would cause the response header fields
RateLimit-RemainingandRateLimit-Resetto have negative values.References: litestar-org/litestar#3776
- OpenAPI: map JSONSchema spec naming convention to snake_case when names from 
schema_extraare not found# Address rejection of
schema_extravalues using JSONSchema spec-compliant key names by mapping between the relevant naming conventions.References: litestar-org/litestar#3766, litestar-org/litestar#3767
- Use correct path template for routes without path parameters#
 Fix a but where, when using
PrometheusConfig.group_path=True, the metrics exporter response content would ignore all paths with no path parameters.References: litestar-org/litestar#3784
- Fix a dangling anyio stream in 
TestClient# Fix a dangling anyio stream in
TestClientthat would cause a resource warningCloses #3834.
References: litestar-org/litestar#3834, litestar-org/litestar#3836
- Fix bug in handling of missing 
more_bodykey in ASGI response# Some frameworks do not include the
more_bodykey in the “http.response.body” ASGI event. According to the ASGI specification, this key should be set toFalsewhen there is no additional body content. Litestar expectsmore_bodyto be explicitly defined, but others might not.This leads to failures when an ASGI framework mounted on Litestar throws error if this key is missing.
References: litestar-org/litestar#3845
- Fix duplicate 
RateLimit-*headers with caching# Fix a bug where
RateLimitMiddlewareduplicate allRateLimit-*headers when handler cache is enabled.References: litestar-org/litestar#3625, litestar-org/litestar#3855
2.12.1#
Released: 2024-09-21Bugfixes#
- Fix base package requiring 
annotated_typesdependency# Fix a bug introduced in #3721 that was released with
2.12.0caused anImportErrorwhen theannotated_typespackage was not installed.References: litestar-org/litestar#3749, litestar-org/litestar#3750
2.12.0#
Released: 2024-09-21Features#
- Support strings in 
media_typeforResponseSpec# Accept strings for the
media_typeparameter ofResponseSpec, making it behave the same way asmedia_type.References: litestar-org/litestar#3728, litestar-org/litestar#3729
- OpenAPI: Allow customizing schema component keys#
 Allow customizing the schema key used for a component in the OpenAPI schema. The supplied keys are enforced to be unique, and it is checked that they won’t be reused across different types.
The keys can be set with the newly introduced
schema_component_keyparameter, which is available onKwargDefinition,Body()andParameter().Two components will be generated:Dataandnot_data#@dataclass class Data: pass @post("/") def handler( data: Annotated[Data, Parameter(schema_component_key="not_data")], ) -> Data: return Data() @get("/") def handler_2() -> Annotated[Data, Parameter(schema_component_key="not_data")]: return Data()
References: litestar-org/litestar#3738
- Raise exception when body parameter is annotated with non-bytes type#
 Add an informative error message to help avoid the common mistake of attempting to use the
bodyparameter to receive validated / structured data by annotating it with a type such aslist[str], instead ofbytes.References: litestar-org/litestar#3740
- OpenAPI: Default to 
latestscalar version# Change the default version of the scalar OpenAPI renderer to
latestReferences: litestar-org/litestar#3747
Bugfixes#
- Fix overzealous warning for greedy middleware 
excludepattern# Fix a bug introduced in
2.11.0(litestar-org/litestar#3700), where the added warning for a greedy pattern use for the middlewareexcludeparameter was itself greedy, and would warn for non-greedy patterns, e.g.^/$.References: litestar-org/litestar#3712
- Fix dangling coroutines in request extraction handling cleanup#
 Fix a bug where, when a required header parameter was defined for a request that also expects a request body, failing to provide the header resulted in a
RuntimeWarning.@post() async def handler(data: str, secret: Annotated[str, Parameter(header="x-secret")]) -> None: return None
If the
x-secretheader was not provided, warning like this would be seen:RuntimeWarning: coroutine 'json_extractor' was never awaited
References: litestar-org/litestar#3734, litestar-org/litestar#3735
- OpenAPI: Correctly handle 
typekeyword# Fix a bug where a type alias created with the
typekeyword would create an empty OpenAPI schema entry for that parameterReferences: litestar-org/litestar#3714, litestar-org/litestar#3715
- OpenAPI: Ensure valid schema keys#
 Ensure that generated schema component keys are always valid according to § 4.8.7.1 of the OpenAPI specification.
References: litestar-org/litestar#3630, litestar-org/litestar#3635
- OpenAPI: Correctly handle 
msgspec.Structtagged unions# Fix a bug where the OpenAPI schema would not include the struct fields implicitly generated by msgspec for its tagged union support.
The tag field of the struct will now be added as a
constof the appropriate type to the schema.References: litestar-org/litestar#3659, litestar-org/litestar#3742
- OpenAPI: Fix Pydantic 1 constrained string with default factory#
 Fix a bug where using a Pydantic model with a
default_factoryset for a constrained string field would raise aSerializationException.class Model(BaseModel): field: str = Field(default_factory=str, max_length=600)
References: litestar-org/litestar#3710, litestar-org/litestar#3721
- OpenAPI/DTO: Fix missing Pydantic 2 computed fields#
 Fix a bug that would lead to Pydantic computed fields to be ignored during schema generation when the model was using a
PydanticDTO.Only thefoofield would be included in the schema#class MyModel(BaseModel): foo: int @computed_field def bar(self) -> int: return 123 @get(path="/", return_dto=PydanticDTO[MyModel]) async def test() -> MyModel: return MyModel.model_validate({"foo": 1})
References: litestar-org/litestar#3656, litestar-org/litestar#3721
- OpenAPI: Fix Pydantic 
json_schema_extraoverrides only being merged partially# Fix a bug where
json_schema_extrawere not reliably extracted from Pydantic models and included in the OpenAPI schema.Only the title set directly on the field would be used for the schema#class Model(pydantic.BaseModel): with_title: str = pydantic.Field(title="new_title") with_extra_title: str = pydantic.Field(json_schema_extra={"title": "more_new_title"}) @get("/example") async def example_route() -> Model: return Model(with_title="1", with_extra_title="2")
References: litestar-org/litestar#3656, litestar-org/litestar#3721
2.11.0#
Released: 2024-08-27Features#
- Use PyJWT instead of python-jose#
 The functionality in
litestar.security.jwtis now backed by PyJWT instead of python-jose, due to the unclear maintenance status of the latter.References: litestar-org/litestar#3684
- DTO: Introduce 
forbid_unknown_fieldsconfig# Add a new config option to
DTOConfig:forbid_unknown_fieldsWhen set toTrue, a validation error response will be returned if the source data contains fields not defined on the model.References: litestar-org/litestar#3690
- DTO: Support 
extra="forbid"model config forPydanticDTO# For Pydantic models with extra=”forbid” in their configuration:
class User(BaseModel): model_config = ConfigDict(extra='ignore') name: str
class User(BaseModel): class Config: extra = "ignore" name: str
forbid_unknown_fieldswill be set toTrueby default.Note
It’s still possible to override this configuration at the DTO level
To facilitate this feature,
get_config_for_model_type()has been added toAbstractDTO, allowing the customization of the base config defined on the DTO factory for a specific model type. It will be called on DTO factory initialization, and receives the concrete DTO model type along side theDTOConfigdefined on the base DTO, which it can alter and return a new version to be used within the DTO instance.References: litestar-org/litestar#3691
- Custom JWT payload classes#
 Support extending the default
Tokenclass used by the JWT backends decode the payload into.Add new
token_clsfield on the JWT auth config classesAdd new
token_clsparameter to JWT auth middlewaresSwitch to using msgspec to convert the JWT payload into instances of the token class
import dataclasses import secrets from typing import Any, Dict from litestar import Request, get from litestar.connection import ASGIConnection from litestar.security.jwt import JWTAuth, Token @dataclasses.dataclass class CustomToken(Token): token_flag: bool = False @dataclasses.dataclass class User: id: str async def retrieve_user_handler(token: CustomToken, connection: ASGIConnection) -> User: return User(id=token.sub) TOKEN_SECRET = secrets.token_hex() jwt_auth = JWTAuth[User]( token_secret=TOKEN_SECRET, retrieve_user_handler=retrieve_user_handler, token_cls=CustomToken, ) @get("/") def handler(request: Request[User, CustomToken, Any]) -> Dict[str, Any]: return {"id": request.user.id, "token_flag": request.auth.token_flag}
import dataclasses import secrets from typing import Any from litestar import Request, get from litestar.connection import ASGIConnection from litestar.security.jwt import JWTAuth, Token @dataclasses.dataclass class CustomToken(Token): token_flag: bool = False @dataclasses.dataclass class User: id: str async def retrieve_user_handler(token: CustomToken, connection: ASGIConnection) -> User: return User(id=token.sub) TOKEN_SECRET = secrets.token_hex() jwt_auth = JWTAuth[User]( token_secret=TOKEN_SECRET, retrieve_user_handler=retrieve_user_handler, token_cls=CustomToken, ) @get("/") def handler(request: Request[User, CustomToken, Any]) -> dict[str, Any]: return {"id": request.user.id, "token_flag": request.auth.token_flag}
References: litestar-org/litestar#3692
- Extended JWT configuration options#
 New JWT backend fields
New JWT middleware parameters
New ``Token.decode`` parameters
Other changes
:meth`Token.decode_payload <~litestar.security.jwt.Token.decode_payload>` has been added to make customization of payload decoding / verification easier without having to re-implement the functionality of the base class method.
See also
References: litestar-org/litestar#3695
- Warn about greedy exclude patterns in middlewares#
 Raise a warning when a middlewares
excludepattern greedily matches all paths.from litestar.middlewares class MyMiddleware(AbstractMiddleware): exclude = ["/", "/home"] async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self.app(scope, receive, send)
Middleware like this would silently be disabled for every route, since the exclude pattern
/matches all paths. If a configuration like this is detected, a warning will now be raised at application startup.References: litestar-org/litestar#3700
- RFC 9457 Problem Details plugin#
 Add a plugin to support RFC 9457 Problem Details responses for error response.
ProblemDetailsPluginenables to selectively or collectively turn responses with an error status code into Problem Detail responses.See also
References: litestar-org/litestar#3199, litestar-org/litestar#3323
Bugfixes#
- Fix creation of 
FormMultiDictinRequest.formto properly handle multi-keys# Fix litestar-org/litestar#3627 by properly handling the creation of
FormMultiDictwhere multiple values are given for a single key, to makeform()match the behaviour of receiving form data via thedatakwarg inside a route handler.Before
@post("/") async def handler(request: Request) -> Any: return (await request.form()).getall("foo") with create_test_client(handler) as client: print(client.post("/", data={"foo": ["1", "2"]}).json()) # [["1", "2"]]
After
@post("/") async def handler(request: Request) -> Any: return (await request.form()).getall("foo") with create_test_client(handler) as client: print(client.post("/", data={"foo": ["1", "2"]}).json()) # ["1", "2"]
References: litestar-org/litestar#3627, litestar-org/litestar#3639
- DTO: Fix inconsistent use of strict decoding mode#
 Fix inconsistent usage of msgspec’s
strictmode in the base DTO backend.strict=Falsewas being used when transferring from builtins, whilestrict=Truewas used transferring from raw data, causing an unwanted discrepancy in behaviour.References: litestar-org/litestar#3685
- Use path template for prometheus metrics#
 Changed previous 1-by-1 replacement logic for
PrometheusMiddleware.group_path=truewith a more robust and slightly faster solution.References: litestar-org/litestar#3687
- Ensure OpenTelemetry captures exceptions in the outermost application layers#
 A bug was fixed that resulted in exception occurring in the outermost application layer not being captured under the current request span, which led to incomplete traces.
References: litestar-org/litestar#3663, litestar-org/litestar#3689
- Fix CSRFMiddleware sometimes setting cookies for excluded paths#
 Fix a bug that would cause
CSRFMiddlewareto set a cookie (which would not be used subsequently) on routes it had been excluded from via a path pattern.References: litestar-org/litestar#3688, litestar-org/litestar#3698
- Make override behaviour consistent between 
signature_namespaceandsignature_types# Ensure that adding signature types to
signature_namespaceandsignature_typesbehaves the same way when a name was already present in the namespace.Both will now issue a warning if a name is being overwritten with a different type. If a name is registered again for the same type, no warning will be given.
Note
You can disable this warning globally by setting
LITESTAR_WARN_SIGNATURE_NAMESPACE_OVERRIDE=0in your environmentReferences: litestar-org/litestar#3681, litestar-org/litestar#3696
2.10.0#
Released: 2024-07-26Features#
- Allow creating parent directories for a file store#
 Allow
mkdirTrue when creating a file store.References: litestar-org/litestar#3526
- Add 
logging_moduleparameter toLoggingConfig# Provide a way in the
logging_moduleto switch easily fromloggingtopicologging.References: litestar-org/litestar#3536, litestar-org/litestar#3578
- Add handler name to exceptions in handler validation#
 Add handler name to exceptions raise by
_validate_handler_function.References: litestar-org/litestar#3575
- Add strict validation support for Pydantic plugin#
 Adds parameters in pydantic plugin to support strict validation and all the
model_dumpargsReferences: litestar-org/litestar#3572, litestar-org/litestar#3608
Bugfixes#
- Fix signature model signatures clash#
 Ensures that the functions used by the signature model itself do not interfere with the signature model created.
References: litestar-org/litestar#3593, litestar-org/litestar#3605
- Correctly handle Annotated 
NewType# Resolves infinite loop in schema generation when a model has an Annotated
NewType.References: litestar-org/litestar#3614, litestar-org/litestar#3615
- Use ASGIConnection instead of 
Requestforflash# Currently, the
FlashPluginexpects therequestparameter to be a type ofRequest. However, there’s no reason it can’t use the parent classASGIConnection.Doing this, allows for flash to be called in guards that expect an
ASGIConnectioninstead ofRequest:def requires_active_user(connection: ASGIConnection, _: BaseRouteHandler) -> None: if connection.user.is_active: return msg = "Your user account is inactive." flash(connection, msg, category="error") raise PermissionDeniedException(msg)
References: litestar-org/litestar#3626
- Allow returning 
Response[None]from head route handlers# Fix a bug where the validation of the return annotation for the
headroute handler was too strict and would not allow returning aResponse[None].References: litestar-org/litestar#3640, litestar-org/litestar#3641
2.9.1#
Released: 2024-06-21Bugfixes#
- Add OPTIONS to the default safe methods for CSRFConfig#
 Add
OPTIONSto the default safe methods forCSRFConfigReferences: litestar-org/litestar#3538
- Prometheus: Capture templated route name for metrics#
 Adding new extraction function for prometheus metrics to avoid high cardinality issue in prometheus, eg having metrics
GET /v1/users/{id}is preferable overGET /v1/users/1,GET /v1/users/2,GET /v1/users/3More info about prometheus high cardinality https://grafana.com/blog/2022/02/15/what-are-cardinality-spikes-and-why-do-they-matter/
References: litestar-org/litestar#3533
- Respect 
base_urlin.websocket_connect# Fix a bug that caused
websocket_connect()/websocket_connect()to not respect thebase_urlset in the client’s constructor, and instead would use the staticws://testerverURL as a base.Also removes most of the test client code as it was unneeded and in the way of this fix :)
Explanation for the last part: All the extra code we had was just proxying method calls to the
httpx.Client/httpx.AsyncClient, while altering the base URL. Since we already set the base URL on the httpx Client’s superclass instance, which in turn does this merging internally, this step isn’t needed at all.References: litestar-org/litestar#3567
- Fix deprecation warning for subclassing route handler decorators#
 Fix an issue where there was a deprecation warning emitted by all route handler decorators. This warning was introduced in
2.9.0to warn about the upcoming deprecation, but should have only applied to user subclasses of the handler classes, and not the built-in ones (get,post, etc.)References: litestar-org/litestar#3552, litestar-org/litestar#3569
- CLI: Don’t call 
rich_click.patchifrich_clickis installed# Don’t call
rich_click.patchifrich_clickis installed. As this monkey patches click globally, it can introduce unwanted side effects. Instead, use conditional imports to refer to the correct library.External libraries will still be able to make use of
rich_clickimplicitly when it’s installed by inheriting fromLitestarGroup/LitestarExtensionGroup, which they will by default.References: litestar-org/litestar#3534, litestar-org/litestar#3570
- Correctly handle 
typing.NewType# When encountering a
typing.NewTypeduring OpenAPI schema generation, we currently treat it as an opaque type. This PR changes the behaviour such that :class`typing.NewType`s are always unwrapped during schema generation.References: litestar-org/litestar#3580
- Encode response content object returned from an exception handler.#
 When an handler raises an exception and exception handler returns a Response with a model (e.g. pydantic) object, ensure that object can be encoded as when returning data from a regular handler.
References: litestar-org/litestar#3585
2.9.0#
Released: 2024-06-02Features#
- Add async 
websocket_connecttoAsyncTestClient# Add async
websocket_connecttoAsyncTestClientReferences: litestar-org/litestar#3133, litestar-org/litestar#3328
- add 
SecretStringandSecretBytesdatastructures# Implement
SecretStringandSecretBytesdata structures to hide sensitive data in tracebacks, etc.References: litestar-org/litestar#1312,, litestar-org/litestar#3248, litestar-org/litestar#3322
- Deprecate subclassing route handler decorators#
 Deprecation for the 2.x release line of the semantic route handler classes removed in #3436.
References: litestar-org/litestar#3439
Bugfixes#
- asgi lifespan msg after lifespan context exception#
 An exception raised within an asgi lifespan context manager would result in a “lifespan.startup.failed” message being sent after we’ve already sent a “lifespan.startup.complete” message. This would cause uvicorn to raise a
STATE_TRANSITION_ERRORassertion error due to their check for that condition , if asgi lifespan is forced (i.e., with$ uvicorn test_apps.test_app:app --lifespan on).E.g.,
During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/peter/.local/share/pdm/venvs/litestar-dj-FOhMr-3.8/lib/python3.8/site-packages/uvicorn/lifespan/on.py", line 86, in main await app(scope, self.receive, self.send) File "/home/peter/.local/share/pdm/venvs/litestar-dj-FOhMr-3.8/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 69, in __call__ return await self.app(scope, receive, send) File "/home/peter/PycharmProjects/litestar/litestar/app.py", line 568, in __call__ await self.asgi_router.lifespan(receive=receive, send=send) # type: ignore[arg-type] File "/home/peter/PycharmProjects/litestar/litestar/_asgi/asgi_router.py", line 180, in lifespan await send(failure_message) File "/home/peter/.local/share/pdm/venvs/litestar-dj-FOhMr-3.8/lib/python3.8/site-packages/uvicorn/lifespan/on.py", line 116, in send assert not self.startup_event.is_set(), STATE_TRANSITION_ERROR AssertionError: Got invalid state transition on lifespan protocol.
This PR modifies
ASGIRouter.lifespan()so that it sends a shutdown failure message if we’ve already confirmed startup.References: litestar-org/litestar#3315
- bug when pydantic==1.10 is installed#
 Fix a bug introduced in #3296 where it failed to take into account that the
pydantic_v2variable could beEmpty.References: litestar-org/litestar#3334, litestar-org/litestar#3335
- OpenAPI router and controller on same app.#
 Fixes an :exc`ImproperlyConfiguredException` where an app that explicitly registers an
OpenAPIControlleron the application, and implicitly uses the OpenAPI router via the OpenAPIConfig object. This was caused by the two different handlers being given the same name as defined inlitestar.constants.PR adds a distinct name for use by the handler that serves
openapi.jsonon the controller.References: litestar-org/litestar#3337, litestar-org/litestar#3338
- pydantic v2 import tests for pydantic v1.10.15#
 Fixes bug with Pydantic V1 environment test where the test was run against v2. Adds assertion for version to the test.
Fixes a bug exposed by above that relied on pydantic not having
v1in the package namespace ifv1is installed. This doesn’t hold true after pydantic’s1.10.15release.References: litestar-org/litestar#3348, litestar-org/litestar#3347
- schema for generic wrapped return types with DTO#
 Fix schema generated for DTOs where the supported type is wrapped in a generic outer type.
Prior behavior of using the
backend.annotationas the basis for generating the openapi schema for the represented type is not applicable for the case where the DTO supported type is wrapped in a generic outer object. In that casebackend.annotationonly represents the type of the attribute on the generic type that holds the DTO supported type annotation.This change detects the case where we unwrap an outer generic type, and rebuilds the generic annotation in a manner appropriate for schema generation, before generating the schema for the annotation. It does this by substituting the DTOs transfer model for the original model in the original annotations type arguments.
References: litestar-org/litestar#2929, litestar-org/litestar#3371
- Ambiguous default warning for no signature default#
 We now only issue a single warning for the case where a default value is supplied via
Parameter()and not via a regular signature default.References: litestar-org/litestar#3372, litestar-org/litestar#3378
- Path param consumed by dependency treated as unconsumed#
 Consider parameters defined in handler dependencies in order to determine if a path parameter has been consumed for openapi generation purposes.
Fixes an issue where path parameters not consumed by the handler, but consumed by dependencies would cause an :exc`ImproperlyConfiguredException`.
References: litestar-org/litestar#3369, litestar-org/litestar#3380
- “name” and “in” should not be included in openapi headers#
 Exclude the “name” and “in” fields from openapi schema generated for headers.
Add
BaseSchemaObject._iter_fields()method that allows schema types to define the fields that should be included in their openapi schema representation and override that method forOpenAPIHeader.References: litestar-org/litestar#3416, litestar-org/litestar#3417
- top-level import of optional package#
 Fix import from
contrib.minijinjawithout handling for case where dependency is not installed.References: litestar-org/litestar#3415, litestar-org/litestar#3418
- regular handler under mounted app#
 Fix an issue where a regular handler under a mounted asgi app would prevent a request from routing through the mounted application if the request path contained the path of the regular handler as a substring.
References: litestar-org/litestar#3429, litestar-org/litestar#3430
- logging to file with structlog#
 Fix and issue with converting
StructLoggingConfigto dict during call toconfigure()when the config object has a custom logger factory that references aTextIOobject, which cannot be pickled.References: litestar-org/litestar#3425
- clear session cookie if new session exceeds 
CHUNK_SIZE# Fix an issue where the connection session cookie is not cleared if the response session is stored across multiple cookies.
References: litestar-org/litestar#3441, litestar-org/litestar#3446
- flash messages were not displayed on Redirect#
 Fix an issue where flashed messages were not shown after a redirect
References: litestar-org/litestar#3325, litestar-org/litestar#3420
- Validation of optional sequence in multipart data with one value#
 A
Sequence[UploadFile] | Nonewould not pass validation when a single value was provided for a structured type, e.g. dataclass.References: litestar-org/litestar#3407, litestar-org/litestar#3408
- field not optional if default value#
 Fix issue where a pydantic v1 field annotation is wrapped with
Optionalif it is marked not required, but has a default value.References: litestar-org/litestar#3471, litestar-org/litestar#3476
- prevent starting multiple responses#
 Prevent the app’s exception handler middleware from starting a response after one has already started.
When something in the middleware stack raises an exception after a “http.response.start” message has already been sent, we end up with long exception chains that obfuscate the original exception.
This change implements tracking of when a response has started, and if so, we immediately raise the exception instead of sending it through the usual exception handling code path.
References: litestar-org/litestar#3479
- logging middleware with multi-body response#
 Prevent logging middleware from failing with a
KeyErrorwhen a response sends multiple “http.response.body” messages.References: litestar-org/litestar#3477, litestar-org/litestar#3478
- handle dto type nested in mapping#
 Added handling for transferring data from a transfer model, to a DTO supported instance when the DTO supported type is nested in a mapping.
I.e, handles this case:
@dataclass class NestedDC: a: int b: str @dataclass class DC: nested_mapping: Dict[str, NestedDC]
References: litestar-org/litestar#3463, litestar-org/litestar#3486
- examples omitted in schema produced by dto#
 Fixes issue where a
BodyKwarginstance provided as metadata to a data type annotation was ignored for OpenAPI schema generation when the data type is managed by a DTO.References: litestar-org/litestar#3505, litestar-org/litestar#3510
- fix handling validation of subscribed generics#
 Fix a bug that would lead to a
TypeErrorwhen subscribed generics were used in a route handler signature and subject to validation.from typing import Generic, TypeVar from litestar import get from litestar.testing import create_test_client T = TypeVar("T") class Foo(Generic[T]): pass async def provide_foo() -> Foo[str]: return Foo() @get("/", dependencies={"foo": provide_foo}) async def something(foo: Foo[str]) -> None: return None with create_test_client([something]) as client: client.get("/")
References: litestar-org/litestar#3519
- exclude static file from schema#
 Exclude static file routes created with
create_static_files_routerfrom the OpenAPI schema by defaultReferences: litestar-org/litestar#3374, litestar-org/litestar#3509
- use re.match instead of re.search for mounted app path (#3501)#
 When mounting an app, path resolution uses
re.searchinstead orre.match, thus mounted app matches any path which contains mount path.References: litestar-org/litestar#3501, litestar-org/litestar#3511
- do not log exceptions twice, deprecate 
traceback_line_limitand fixpretty_print_tty# The wording of the log message, when logging an exception, has been updated.
For structlog, the
tracebackfield in the log message (which contained a truncated stacktrace) has been removed. Theexceptionfield is still around and contains the full stacktrace.The option
traceback_line_limithas been deprecated. The value is now ignored, the full stacktrace will be logged.
References: litestar-org/litestar#3228, litestar-org/litestar#3507
- YAML schema dump#
 Fix an issue in the OpenAPI YAML schema dump logic of
OpenAPIControllerwhere the endpoint for the OpenAPI YAML schema file returns an empty response if a request has been made to the OpenAPI JSON schema previously due to an incorrect variable check.References: litestar-org/litestar#3537
2.8.3#
Released: 2024-05-06Bugfixes#
- Fix improper limitation of a pathname to a restricted directory#
 Fix a path traversal vulnerability disclosed in litestar-org/litestar
References:
- Remove use of asserts for control flow.#
 #3347 introduced a new pattern to differentiate between Pydantic v1 and v2 installs, however it relies on using assert which is an issue as can optimised away.
This PR changes the approach to manually throw an ImportError instead.
References: litestar-org/litestar#3354, litestar-org/litestar#3359
- schema for generic wrapped return types with DTO#
 Fix schema generated for DTOs where the supported type is wrapped in a generic outer type.
References: litestar-org/litestar#2929, litestar-org/litestar#3371
- Ambiguous default warning for no signature default#
 We now only issue a single warning for the case where a default value is supplied via Parameter() and not via a regular signature default.
References: litestar-org/litestar#3372, litestar-org/litestar#3378
- Path param consumed by dependency treated as unconsumed#
 Consider parameters defined in handler dependencies in order to determine if a path parameter has been consumed for openapi generation purposes.
Fixes an issue where path parameters not consumed by the handler, but consumed by dependencies would cause an ImproperlyConfiguredException.
References: litestar-org/litestar#3369, litestar-org/litestar#3380
- Solve a caching issue in CacheControlHeader#
 Fixes an issue causing return of invalid values from cache.
References: litestar-org/litestar#3383
- “name” and “in” should not be included in openapi headers#
 Exclude the “name” and “in” fields from openapi schema generated for headers.
References: litestar-org/litestar#3416, litestar-org/litestar#3417
- top-level import of optional package#
 Fix import from contrib.minijinja without handling for case where dependency is not installed.
References: litestar-org/litestar#3415, litestar-org/litestar#3418
- regular handler under mounted app#
 Fix an issue where a regular handler under a mounted asgi app would prevent a request from routing through the mounted application if the request path contained the path of the regular handler as a substring.
References: litestar-org/litestar#3429, litestar-org/litestar#3430
- logging to file with structlog#
 PR fixes issue with converting StructLoggingConfig to dict during call to configure() when the config object has a custom logger factory that references a TextIO object, which cannot be pickled.
References: litestar-org/litestar#3425
- clear session cookie if new session gt CHUNK_SIZE#
 Fix an issue where the connection session cookie is not cleared if the response session is stored across multiple cookies.
References: litestar-org/litestar#3441, litestar-org/litestar#3446
- flash messages were not displayed on Redirect#
 Fixes issue where flash messages were not displayed on redirect.
References: litestar-org/litestar#3325, litestar-org/litestar#3420
- Validation of optional sequence in multipart data with one value#
 A Sequence[UploadFile] | None would not pass validation when a single value was provided for a structured type, e.g. dataclass.
References: litestar-org/litestar#3407, litestar-org/litestar#3408
2.8.2#
Released: 2024-04-09Bugfixes#
- pydantic v2 import tests for pydantic v1.10.15#
 Fixes bug with Pydantic v1 environment test causing the test to run against v2. Adds assertion for version to the test.
Fixes a bug exposed by above that relied on Pydantic not having v1 in the package namespace if v1 is installed. This doesn’t hold true after Pydantic’s 1.10.15 release.
Moves application environment tests from the release job into the normal CI run.
References: litestar-org/litestar#3348, litestar-org/litestar#3347
2.8.1#
Released: 2024-04-08Bugfixes#
- ASGI lifespan msg after lifespan context exception#
 An exception raised within an asgi lifespan context manager would result in a “lifespan.startup.failed” message
This PR modifies ASGIRouter.lifespan() so that it sends a shutdown failure message if we’ve already confirmed startup.
References: litestar-org/litestar#3315
- Fix when pydantic==1.10 is installed#
 This PR fixes a bug introduced in #3296 where it failed to take into account that the pydantic_v2 variable could be Empty.
References: litestar-org/litestar#3334, litestar-org/litestar#3335
- OpenAPI router and controller on same app.#
 Fixes an ImproperlyConfiguredException where an app that explicitly registers an OpenAPIController on the application, and implicitly uses the OpenAPI router via the OpenAPIConfig object. This was caused by the two different handlers being given the same name as defined in litestar.constants.
PR adds a distinct name for use by the handler that serves openapi.json on the controller.
References: litestar-org/litestar#3337, litestar-org/litestar#3338
2.8.0#
Released: 2024-04-05Features#
- Add 
pathparameter to Litestar application class# Exposes
parameteratLitestarapplication class levelReferences: litestar-org/litestar#3314
- Allow for console output to be silenced#
 Introduces optional environment variables that allow customizing the “Application” name displayed in the console output and suppressing the initial
from_envor theRichinfo table at startup.Provides flexibility in tailoring the console output to better integrate Litestar into larger applications or CLIs.
References: litestar-org/litestar#3180
- Add flash plugin#
 Adds a flash plugin akin to Django or Flask that uses the request state
References: litestar-org/litestar#1455, litestar-org/litestar#3145
- Use memoized 
request_classandresponse_classvalues# Uses memoized
request_classandresponse_classvaluesReferences: litestar-org/litestar#3205
- Enable codegen backend by default#
 Enables the codegen backend for DTOs introduced in litestar-org/litestar#2388 by default.
References: litestar-org/litestar#3215
- Added precedence of CLI parameters over envs#
 Adds precedence of CLI parameters over environment variables. Before this change, environment variables would take precedence over CLI parameters.
Since CLI parameters are more explicit and are set by the user, they should take precedence over environment variables.
References: litestar-org/litestar#3188, litestar-org/litestar#3190
- Only print when terminal is 
TTYenabled# Sets
LITESTAR_QUIET_CONSOLEandLITESTAR_APP_NAMEin the autodiscovery function. Also prevents the tabular console output from printing when the terminal is notTTYReferences: litestar-org/litestar#3219
- Support 
schema_extrainParameterand Body# Introduces a way to modify the generated OpenAPI spec by adding a
schema_extraparameter to the Parameter and Body classes. Theschema_extraparameter accepts adict[str, Any]where the keys correspond to the keyword parameter names in Schema, and the values are used to override items in the generated Schema object.Provides a convenient way to customize the OpenAPI documentation for inbound parameters.
References: litestar-org/litestar#3204
- Add 
typing.TypeVarexpansion# Adds a method for TypeVar expansion on registration This allows the use of generic route handler and generic controller without relying on forward references.
References: litestar-org/litestar#3242
- Add 
LITESTAR_prefix beforeWEB_CONCURRENCYenv option# Adds
LITESTAR_prefix before theWEB_CONCURRENCYenvironment optionReferences: litestar-org/litestar#3227
- Warn about ambiguous default values in parameter specifications#
 As discussed in litestar-org/litestar#3280, we want to warn about, and eventually disallow specifying parameter defaults in two places.
To achieve this, 2 warnings are added:
A deprecation warning if a default is specified when using
Annotated:param: Annotated[int, Parameter(..., default=1)]instead ofparam: Annotated[int, Parameter(...)] = 1An additional warning in the above case if two default values are specified which do not match in value:
param: Annotated[int, Parameter(..., default=1)] = 2
In a future version, the first one should result in an exception at startup, preventing both of these scenarios.
References: litestar-org/litestar#3283
- Support declaring 
DTOFieldviaAnnotated# Deprecates passing
DTOFieldvia[pydantic]extra.References: litestar-org/litestar#2351, litestar-org/litestar#3289
- Add “TRACE” to HttpMethod enum#
 Adds the
TRACEHTTP method toHttpMethodenumReferences: litestar-org/litestar#3294
- Pydantic DTO non-instantiable types#
 Simplifies the type that is applied to DTO transfer models for certain Pydantic field types. It addresses
JsonValue,EmailStr,IPvAnyAddress/IPvAnyNetwork/IPvAnyInterfacetypes by using appropriate type annotations on the transfer models to ensure compatibility with msgspec serialization and deserialization.References: litestar-org/litestar#3296
Bugfixes#
- Unique schema names for nested models (#3134)#
 Fixes an issue where nested models beyond the
max_nested_depthwould not have unique schema names in the OpenAPI documentation. The fix appends the nested model’s name to theunique_nameto differentiate it from the parent model.References: litestar-org/litestar#3134, litestar-org/litestar#3136
- Remove duplicate 
rich-clickconfig options# Removes duplicate config options from click cli
References: litestar-org/litestar#3274
- Fix Pydantic 
json_schema_extraexamples.# Fixes a regression introduced in
2.7.0where an example for a field provided in Pydantic’sField.json_schema_extrawould cause an error.References: litestar-org/litestar#3277, litestar-org/litestar#3281
- Set default on schema from 
FieldDefinition# Consider the following:
def get_foo(foo_id: int = 10) -> None: ...
In such cases, no
KwargDefinitionis created since there is no metadata provided viaAnnotated. The default is still parsed, and set on the generatedFieldDefinition, however theSchemaCreatorcurrently only considers defaults that are set onKwargDefinition.So in such cases, we should fallback to the default set on the
FieldDefinitionif there is a valid default value.References: litestar-org/litestar#3278, litestar-org/litestar#3280
- Custom types cause serialisation error in exception response with non-JSON media-type#
 Fixes a bug when using a non-JSON media type (e.g.,
text/plain),ValidationException’s would not get serialized properly because they would ignore customtype_encoders.References: litestar-org/litestar#3192, litestar-org/litestar#3284
- Ensure default values are always represented in schema for dataclasses and 
msgspec.Structs# Fixes a bug that would prevent default values for dataclasses and
msgspec.Structs to be included in the OpenAPI schema.References: litestar-org/litestar#3201, litestar-org/litestar#3285
- Pydantic v2 error handling/serialization when for non-Pydantic exceptions#
 Fixes a bug that would cause a
TypeErrorwhen non-Pydantic errors are raised during Pydantic’s validation process while using DTOs.References: litestar-org/litestar#2365, litestar-org/litestar#3286
- Fix OpenAPI schema generation for paths with path parameters of different types on the same path#
 Fixes a bug that would cause no OpenAPI schema to be generated for paths with path parameters that only differ on the path parameter type, such as
/{param:int}and/{param:str}. This was caused by an internal representation issue in Litestar’s routing system.References: litestar-org/litestar#2700, litestar-org/litestar#3293
- Document unconsumed path parameters#
 Fixes a bug where path parameters not consumed by route handlers would not be included in the OpenAPI schema.
This could/would not include the
{param}in the schema, yet it is still required to be passed when calling the path.References: litestar-org/litestar#3290, litestar-org/litestar#3295
2.7.1#
Released: 2024-03-22Bugfixes#
- replace TestClient.__enter__ return type with Self#
 TestClient.__enter__andAsyncTestClient.__enter__returnSelf. If you inheritTestClient, its__enter__method should return derived class’s instance unless override the method.Selfis a more flexible return type.References: litestar-org/litestar#3194
- use the full path for fetching openapi.json#
 This specifies the
spec-urlandapiDescriptionUrlof Rapidoc, and Stoplight Elements as absolute paths relative to the root of the site.This ensures that both of the send the request for the JSON of the OpenAPI schema to the right endpoint.
References: litestar-org/litestar#3047, litestar-org/litestar#3196
- JSON schema 
exampleswere OpenAPI formatted# The generated
examplesin JSON schema objects were formatted as:"examples": { "some-id": { "description": "Lorem ipsum", "value": "the real beef" } }
However, above is OpenAPI example format, and must not be used in JSON schema objects. Schema objects follow different formatting:
"examples": [ "the real beef" ]
This is referenced at least from parameters, media types and components.
The technical change here is to define
Schema.examplesaslist[Any]instead oflist[Example]. Examples can and must still be defined aslist[Example]for OpenAPI objects (e.g.Parameter,Body) but for JSON schemaexamplesthe code now internally generates/convertslist[Any]format instead.Extra confusion here comes from the OpenAPI 3.0 vs OpenAPI 3.1 difference. OpenAPI 3.0 only allowed
example(singular) field in schema objects. OpenAPI 3.1 supports the full JSON schema 2020-12 spec and soexamplesarray in schema objects.Both
exampleandexamplesseem to be supported, though the former is marked as deprecated in the latest specs.This can be tested over at https://editor-next.swagger.io by loading up the OpenAPI 3.1 Pet store example. Then add
examplesincomponents.schemas.Petusing the both ways and see the Swagger UI only render the example once it’s properly formatted (it ignores is otherwise).References: litestar-org/litestar#2849, litestar-org/litestar#3224
- queue_listener handler for Python >= 3.12#
 Fix the
queue_listenerhandler for Python 3.12
Python 3.12 introduced a new way to configure
QueueHandlerandQueueListenervialogging.config.dictConfig(). As described in the logging documentation.The listener still needs to be started & stopped, as previously. To do so, we’ve introduced
LoggingQueueListener.And as stated in the doc: * Any custom queue handler and listener classes will need to be defined with the same initialization signatures as QueueHandler and QueueListener.
References: litestar-org/litestar#2954, litestar-org/litestar#3185
- extend openapi meta collected from domain models#
 FieldDefinitions pack any OpenAPI metadata onto aKwargDefinitioninstance when types are parsed from domain models.When we produce a DTO type, we transfer this meta from the KwargDefinition to a msgspec.Meta instance, however so far this has only included constraints, not attributes such as descriptions, examples and title.
This change ensures that we transfer the openapi meta for the complete intersection of fields that exist on b oth KwargDefinition and Meta.
References: litestar-org/litestar#3232, litestar-org/litestar#3237
- kwarg ambiguity exc msg for path params#
 Fixes the way we construct the exception message when there is a kwarg ambiguity detected for path parameters.
References: litestar-org/litestar#3261
2.7.0#
Released: 2024-03-10Features#
- Support 
ResponseSpec(..., examples=[...])# Allow defining custom examples for the responses via
ResponseSpec. The examples set this way are always generated locally, for each response: Examples that go within the schema definition cannot be set by this.{ "paths": { "/": { "get": { "responses": { "200": { "content": { "application/json": { "schema": {}, "examples": "..."}} }} }} } }
References: litestar-org/litestar#3068, litestar-org/litestar#3100
- support “+json”-suffixed response media types#
 Automatically encode responses with media type of the form
application/<something>+jsonas json.References: litestar-org/litestar#3088, litestar-org/litestar#3096
- Allow reusable 
Routerinstances# It was not possible to re-attach a router instance once it was attached. This makes that possible.
The router instance now gets deepcopied when it’s registered to another router.
The application startup performance gets a hit here, but the same approach is already used for controllers and handlers, so this only harmonizes the implementation.
References: litestar-org/litestar#3012, litestar-org/litestar#3103
- only display path in 
ValidationExceptions# Fix an issue where
ValidationExceptionexposes the full URL in the error response, leaking internal IP(s) or other similar infra related information.References: litestar-org/litestar#3061, litestar-org/litestar#3064
- expose 
request_classto other layers# Expose
request_classto other layersReferences: litestar-org/litestar#3125
- expose 
websocket_class# Expose
websocket_classto other layersReferences: litestar-org/litestar#3152
- Add 
type_decodersto Router and route handlers# Add
type_decodersto__init__method for handler, routers and decorators to keep consistency withtype_encodersparameterReferences: litestar-org/litestar#3153
- Pass 
type_decodersinWebsocketListenerRouteHandler# Pass
type_decodersto parent’s__init__inWebsocketListenerRouteHandlerinit, otherwisetype_decoderswill beNonereplace params order in docs,__init__(decoders before encoders)References: litestar-org/litestar#3162
- 3116 enhancement session middleware#
 For server side sessions, the session id is now generated before the route handler. Thus, on first visit, a session id will be available inside the route handler’s scope instead of afterwards A new abstract method
get_session_idwas added toBaseSessionBackendsince this method will be called for both ClientSideSessions and ServerSideSessions. Only for ServerSideSessions it will return an actual id. Usingrequest.set_session(...)will return the session id for ServerSideSessions and None for ClientSideSessions The session auth MiddlewareWrapper now refers to the Session Middleware via the configured backend, instead of it being hardcodedReferences: litestar-org/litestar#3116, litestar-org/litestar#3127
- make random seed for openapi example generation configurable#
 Allow random seed used for generating the examples in the OpenAPI schema (when
create_examplesis set toTrue) to be configured by the user. This is related to litestar-org/litestar#3059 however whether this change is enough to close that issue or not is not confirmed.References: litestar-org/litestar#3166
- generate openapi components schemas in a deterministic order#
 Ensure that the insertion into the
Components.schemasdictionary of the OpenAPI spec will be in alphabetical order (based on the normalized name of theSchema).References: litestar-org/litestar#3172
Bugfixes#
- missing cors headers in response#
 Set CORS Middleware headers as per spec. Addresses issues outlined on litestar-org/litestar#3178
References: litestar-org/litestar#3178, litestar-org/litestar#3179
- sending empty data in sse in js client#
 Fix an issue with SSE where JavaScript clients fail to receive an event without data. The spec is not clear in whether or not an event without data is ok. Considering the EventSource “client” is not ok with it, and that it’s so easy DX-wise to make the mistake not explicitly sending it, this change fixes it by defaulting to the empty-string
References: litestar-org/litestar#3176
2.6.3#
Released: 2024-03-04Bugfixes#
- Pydantic V1 schema generation for PrivateAttr in GenericModel#
 Fixes a bug that caused a
NameErrorwhen a Pydantic V1GenericModelhas a private attribute of which the type annotation cannot be resolved at the time of schema generation.References: litestar-org/litestar#3150, litestar-org/litestar#3161
2.6.2#
Released: 2024/03/02Bugfixes#
- DTO msgspec meta constraints not being included in transfer model#
 Fix an issue where msgspec constraints set in
msgspec.Metawould not be honoured by the DTO.In the given example, the
min_length=3constraint would be ignored by the model generated byMsgspecDTO.from typing import Annotated import msgspec from litestar import post from litestar.dto import MsgspecDTO class Request(msgspec.Struct): foo: Annotated[str, msgspec.Meta(min_length=3)] @post("/example/", dto=MsgspecDTO[Request]) async def example(data: Request) -> Request: return data
Constraints like these are now transferred.
Two things to note are:
For DTOs with
DTOConfig(partial=True)we cannot transfer the length constraints as they are only supported on fields that as subtypes ofstr,bytesor a collection type, butpartial=Truesets all fields asT | UNSETFor the
PiccoloDTO, fields which are not required will also drop the length constraints. A warning about this will be raised here.
References: litestar-org/litestar#3026, litestar-org/litestar#3113
- Missing control header for static files#
 Fix an issue where a
cache_controlthat is set on a router created bycreate_static_files_routerwasn’t passed to the generated handlerReferences: litestar-org/litestar#3129, litestar-org/litestar#3131
- Fix OpenAPI schema generation for Pydantic v2 constrained 
Secrettypes# Fix schema generation for
pydantic.SecretStrandpydantic.SecretByteswhich, when constrained, would not be recognised as such with Pydantic V2 since they’re not subtypes of their respective bases anymore.References: litestar-org/litestar#3148, litestar-org/litestar#3149
- Fix OpenAPI schema generation for Pydantic private attributes#
 Fix a bug that caused a
NameErrorwhen trying to resolve forward references in Pydantic private fields.Although private fields were respected excluded from the schema, it was still attempted to extract their type annotation. This was fixed by not relying on
typing.get_type_hintsto get the type information, but instead using Pydantic’s own APIs, allowing us to only extract information about the types of relevant fields.References: litestar-org/litestar#3150, litestar-org/litestar#3151
- OpenAPI description not set for UUID based path parameters in OpenAPI#
 Resolved a bug where the description was not set for UUID-based path parameters in OpenAPI due to the reason mentioned in the issue.
References: litestar-org/litestar#2967, litestar-org/litestar#3118
- Fix 
RedisStoreclient created withwith_clientunclosed# Fix a bug where, when a
RedisStorewas created with thewith_client()method, that client wasn’t closed explicitlyReferences: litestar-org/litestar#3083, litestar-org/litestar#3111
2.6.1#
Released: 2024/02/14Bugfixes#
- SQLAlchemy: Use IntegrityError instead of deprecated ConflictError#
 Updated the repository to return
IntegrityErrorinstead of the now deprecatedConflictErrorReferences: litestar-org/litestar#3094
- Remove usage of deprecated static_files property#
 Remove the usage of the deprecated
Litestar.static_files_configinLitestar.__init__.References: litestar-org/litestar#3087
- Sessions: Fix cookie naming for short cookies#
 Previously, cookie names always had a suffix of the form
"-{i}"appended to them. With this change, the suffix is omitted if the cookie is short enough (< 4 KB) to not be split into multiple chunks.References: litestar-org/litestar#3090, litestar-org/litestar#3095
- Static files: Fix path resolution for windows#
 Fix an issue with the path resolution on Windows introduced in litestar-org/litestar#2960 that would lead to 404s
References: litestar-org/litestar#3102
- Fix logging middleware with structlog causes application to return a 
500when request body is malformed# Gracefully handle malformed request bodies during parsing when using structlog; Instead of erroring out and returning a
500, the raw body is now being used when an error occurs during parsingReferences: litestar-org/litestar#3063, litestar-org/litestar#3109
- OpenAPI: Generate correct response schema for 
ResponseSpec(None)# Explicitly declaring
responses={...: ResponseSpec(None)}used to generate OpenAPI acontentproperty, when it should be omitted.References: litestar-org/litestar#3069, litestar-org/litestar#3098
- Prevent exception handlers from extracting details from non-Litestar exceptions#
 Fix a bug where exception classes that had a
status_codeattribute would be treated as Litestar exceptions and details from them would be extracted and added to the exception response.References: litestar-org/litestar#3082, litestar-org/litestar#3106
2.6.0#
Released: 2024/02/06Features#
- Enable disabling configuring 
rootlogger withinLoggingConfig# The option
configure_root_loggerwas added toLoggingConfigattribute. It is enabled by default to not implement a breaking change.When set to
Falsetherootlogger will not be modified forloggingorpicologgingloggers.References: litestar-org/litestar#2969
- Simplified static file handling and enhancements#
 Static file serving has been implemented with regular route handlers instead of a specialised ASGI app. At the moment, this is complementary to the usage of
StaticFilesConfigto maintain backwards compatibility.This achieves a few things:
Circumvents special casing needed in the routing logic for the static files app
Removes the need for a
static_files_configattribute on the appRemoves the need for a special
url_for_static_asset()method on the app since route_reverse can be used instead
Additionally:
Most router options can now be passed to the
create_static_files_router(), allowing further customisationA new
resolve_symlinksflag has been added, defaulting toTrueto keep backwards compatibility
Usage
Instead of
app = Litestar( static_files_config=[StaticFilesConfig(path="/static", directories=["some_dir"])] )
You can now simply use
app = Litestar( route_handlers=[ create_static_files_router(path="/static", directories=["some_dir"]) ] )
See also
References: litestar-org/litestar#2629, litestar-org/litestar#2960
- Exclude Piccolo ORM columns with 
secret=TruefromPydanticDTOoutput# For Piccolo columns with
secret=Trueset, correspondingPydanticDTOattributes will be marked asWRITE_ONLYto prevent the column being included inreturn_dtoReferences: litestar-org/litestar#3030
- Allow discovering registered plugins by their fully qualified name#
 PluginRegistryPluginRegistry` now supports retrieving a plugin by its fully qualified name.
References: litestar-org/litestar#3027
- Support externally typed classes as dependency providers#
 Implement a new
DIPluginclass that allows the generation of signatures for arbitrary types where their signature cannot be extracted from the type’s__init__methodImplement
DIPlugins for Pydantic and Msgspec to allow using their respective modelled types as dependency providers. These plugins will be registered by default
References: litestar-org/litestar#2979, litestar-org/litestar#3066
- Add structlog plugin#
 A Structlog plugin to make it easier to configure structlog in a single place.
The plugin:
Detects if a logger has
setLevelbefore callingSet even message name to be init-cap
Add
set_levelinterface to configAllows structlog printer to detect if console is TTY enabled. If so, a Struglog color formatter with Rich traceback printer is used
Auto-configures stdlib logger to use the structlog logger
References: litestar-org/litestar#2943
- Add reload-include and reload-exclude to CLI run command#
 The options
reload-excludeandreload-includewere added to the CLIruncommand to explicitly in-/exclude specific paths from the reloading watcher.References: litestar-org/litestar#2875, litestar-org/litestar#2973
2.5.5#
Released: 2024/02/04Bugfixes#
- Fix scope 
statekey handling# Fix a regression introduced in #2751 that would wrongfully assume the
statekey is always present within the ASGI Scope. This is only the case when the Litestar root application is invoked first, since we enforce such a key there, but the presence of that key is not actually guaranteed by the ASGI spec and some servers, such as hypercorn, do not provide it.References: litestar-org/litestar#3070
2.5.4#
Released: 2024/01/31Bugfixes#
- Handle 
KeyErrorwhen root_path is not present in ASGI scope# Nginx Unit ASGI server does not set “root_path” in the ASGI scope, which is expected as part of the changes done in #3039. This PR fixes the assumption that the key is always present and instead tries to optionally retrieve it.
KeyError on GET / 'root_path'
References: litestar-org/litestar#3051
- ServerSentEvent typing error#
 fixes small typing error:
error: Argument 1 to "ServerSentEvent" has incompatible type "AsyncIterable[ServerSentEventMessage]"; expected "str | bytes | Iterable[str | bytes] | Iterator[str | bytes] | AsyncIterable[str | bytes] | AsyncIterator[str | bytes]" [arg-type]
inside
test_ssethere was aAnyI changed to trigger the test then solved it.References: litestar-org/litestar#3048
2.5.3#
Released: 2024/01/29Bugfixes#
- Handle diverging ASGI 
root_pathbehaviour# Uvicorn 0.26.0 introduced a breaking change in its handling of the ASGI
root_pathbehaviour, which, while adhering to the spec, diverges from the interpretation of other ASGI servers of this aspect of the spec (e.g. hypercorn and daphne do not follow uvicorn’s interpretation as of today). A fix was introduced that ensures consistent behaviour of applications in any case.References: litestar-org/litestar#3041, litestar-org/litestar#3039
2.5.2#
Released: 2024/01/27Bugfixes#
- Ensure 
MultiDictandImmutableMultiDictcopy methods return the instance’s type# Ensure
MultiDictandImmutableMultiDictcopy methods return a new instance ofMultiDictandImmutableMultiDict. Previously, these would return amultidict.MultiDictinstance.References: litestar-org/litestar#2549, litestar-org/litestar#3009
- Ensure 
exceptiongroupis installed on Python 3.11# Add the exceptiongroup package as a required dependency on Python
<3.11(previously<3.10) as a backport of Exception GroupsReferences: litestar-org/litestar#3029, litestar-org/litestar#3035
2.5.1#
Released: 2024/01/18Bugfixes#
- Fix OpenAPI schema generation for Union of multiple 
msgspec.Structs andNone# The following code would raise a
TypeErrorimport msgspec from litestar import get class StructA(msgspec.Struct): pass class StructB(msgspec.Struct): pass @get("/") async def handler() -> StructA | StructB | None: return StructA()
References: litestar-org/litestar#2971, litestar-org/litestar#2982
- Fix misleading error message for missing dependencies provide by a package extra#
 Ensure that
MissingDependencyExceptionincludes the correct name of the package to install if the package name differs from the Litestar package extra. (e.g.pip install 'litestar[jinja]'vspip install jinja2). Previously the exception assumed the same name for both the package and package-extra name.References: litestar-org/litestar#2921
- Fix OpenAPI schema file upload schema types for swagger#
 Always set
formatasbinaryFix schema for swagger with multiple files, which requires the type of the request body schema to be
objectwithpropertiesinstead of a schema of typearrayanditems.
References: litestar-org/litestar#2628, litestar-org/litestar#2745
2.5.0#
Released: 2024/01/06Features#
- Postgres channels backends#
 Two new channel backends were added to bring Postgres support:
AsyncPgChannelsBackend, using the asyncpg driver andPsycoPgChannelsBackendusing the psycopg3 async driver.See also
References: litestar-org/litestar#2803
- Add 
--schemaand--excludeoption tolitestar routeCLI command# Two new options were added to the
litestar routeCLI command:--schema, to include the routes serving OpenAPI schema and docs--excludeto exclude routes matching a specified pattern
See also
Read more in the CLI cli section.
References: litestar-org/litestar#2886
Bugfixes#
- Fix serialization of custom types in exception responses#
 Fix a bug that would lead to a
SerializationExceptionwhen custom types were present in an exception response handled by the built-in exception handlers.class Foo: pass @get() def handler() -> None: raise ValidationException(extra={"foo": Foo("bar")}) app = Litestar(route_handlers=[handler], type_encoders={Foo: lambda foo: "foo"})
The cause was that, in examples like the one shown above,
type_encoderswere not resolved properly from all layers by the exception handling middleware, causing the serializer to throw an exception for an unknown type.References: litestar-org/litestar#2867, litestar-org/litestar#2941
- Fix SSE reverting to default 
event_typeafter 1st message# The
event_typeset within an SSE returned from a handler would revert back to a default after the first message sent:@get("/stream") async def stream(self) -> ServerSentEvent: async def gen() -> AsyncGenerator[str, None]: c = 0 while True: yield f"<div>{c}</div>\n" c += 1 return ServerSentEvent(gen(), event_type="my_event")
In this example, the event type would only be
my_eventfor the first message, and fall back to a default afterwards. The implementation has been fixed and will now continue sending the set event type for all messages.References: litestar-org/litestar#2877, litestar-org/litestar#2888
- Correctly handle single file upload validation when multiple files are specified#
 Uploading a single file when the validation target allowed multiple would cause a
ValidationException:class FileUpload(Struct): files: list[UploadFile] @post(path="/") async def upload_files_object( data: Annotated[FileUpload, Body(media_type=RequestEncodingType.MULTI_PART)] ) -> list[str]: pass
This could would only allow for 2 or more files to be sent, and otherwise throw an exception.
References: litestar-org/litestar#2939, litestar-org/litestar#2950
- Fix trailing messages after unsubscribe in channels#
 Fix a bug that would allow some channels backend to receive messages from a channel it just unsubscribed from, for a short period of time, due to how the different brokers handle unsubscribes.
await backend.subscribe(["foo", "bar"]) # subscribe to two channels await backend.publish( b"something", ["foo"] ) # publish a message to a channel we're subscribed to # start the stream after publishing. Depending on the backend # the previously published message might be in the stream event_generator = backend.stream_events() # unsubscribe from the channel we previously published to await backend.unsubscribe(["foo"]) # this should block, as we expect messages from channels # we unsubscribed from to not appear in the stream anymore print(anext(event_generator))
Backends affected by this were in-memory, Redis PubSub and asyncpg. The Redis stream and psycopg backends were not affected.
References: litestar-org/litestar#2894
Other changes#
- Improve performance of threaded synchronous execution#
 Performance of threaded synchronous code was improved by using the async library’s native threading helpers instead of anyio. On asyncio,
asyncio.loop.run_in_executor()is now used and on triotrio.to_thread.run_sync().Beneficiaries of these performance improvements are:
Synchronous route handlers making use of
sync_to_thread=TrueSynchronous dependency providers making use of
sync_to_thread=TrueSynchronous SSE generators
Large file uploads where the
max_spool_sizeis exceeded and the spooled temporary file has been rolled to diskFileandASGIFileResponse
References: litestar-org/litestar#2937
2.4.5#
Released: 2023/12/23Bugfixes#
- Fix validation of empty payload data with default values#
 Prior to this fix, a handler like:
@post(path="/", sync_to_thread=False) def test(data: str = "abc") -> dict: return {"foo": data}
$ curl localhost:8000 -X POSTwould return a client error like:
{"status_code":400,"detail":"Validation failed for POST http://localhost:8000/","extra":[{"message":"Expected `str`, got `null`","key":"data","source":"body"}]}
References: litestar-org/litestar#2902, litestar-org/litestar#2903
- Support for returning 
Response[None]with a204status code from a handler# Returning a
Response[None]from a route handler for a response with a204now works as expected without resulting in anImproperlyConfiguredExceptionReferences: litestar-org/litestar#2914, litestar-org/litestar#2915
- Fix error message of 
get_logger_placeholder()# Using a method on
Request.loggerwhen not setting alogging_configon the application would result in a non-descriptiveTypeError. AnImproperlyConfiguredExceptionwith an explanation is now raised instead.References: litestar-org/litestar#2919
2.4.4#
Released: 2023/12/13Bugfixes#
- Support non-valid identifier as serialization target name#
 Fix a bug where DTOs would raise a
TypeError: __slots__ must be identifiersduring serialization, if a non-valid identifier (such asfield-name)was used for field renaming.References: litestar-org/litestar#2845, litestar-org/litestar#2850
- Fix regression signature validation for DTO validated types#
 Fix a regression introduced in
2.0.0rc1that would cause data validated by the DTO to be validated again by the signature model.References: litestar-org/litestar#2149, litestar-org/litestar#2854
- Fix regression in OpenAPI schema key names#
 Fix a regression introduced in
2.4.0regarding the naming of OpenAPI schema keys, in which a change was introduced to the way that keys for the OpenAPI components/schemas objects were calculated to address the possibility of name collisions.This behaviour was reverted for the case where a name has no collision, and now only introduces extended keys for the case where there are multiple objects with the same name, a case which would previously result in an exception.
References: litestar-org/litestar#2804, litestar-org/litestar#2841
- Fix regression in OpenAPI handling of routes with multiple handlers#
 Fix a regression introduced in
2.4.3causing two routes registered with the same path, but different methods to break OpenAPI schema generation due to both of them having the same value for operation ID.References: litestar-org/litestar#2863, litestar-org/litestar#2864
- Fix OpenAPI schema generation for recursive models#
 Fix an issue that would lead to a
RecursionErrorwhen including nested models in the OpenAPI schema.References: litestar-org/litestar#2429, litestar-org/litestar#2869
2.4.3#
Released: 2023/12/07Bugfixes#
- Fix OpenAPI schema for 
Literal | Noneunions# Fix a bug where an incorrect OpenAPI schema was generated generated when any
Literal | None-union was present in an annotation.For example
type: Literal["sink", "source"] | None
would generate
{ "name": "type", "in": "query", "schema": { "type": "string", "enum": [ "sink", "source", null ] } }
References: litestar-org/litestar#2812, litestar-org/litestar#2818
- Fix advanced-alchemy 0.6.0 compatibility issue with 
touch_updated_timestamp# Fix an incorrect import for
touch_updated_timestampof Advanced Alchemy, introduced in Advanced-Alchemy version 0.6.0.References: litestar-org/litestar#2843
2.4.2#
Released: 2023/12/02Bugfixes#
- Fix OpenAPI handling of parameters with duplicated names#
 Fix a bug where schema generation would consider two parameters with the same name but declared in different places (eg., header, cookie) as an error.
References: litestar-org/litestar#2662, litestar-org/litestar#2788
- Fix late failure where 
DTODatais used without a DTO# Fix an issue where a handler would be allowed to be registered with a
DTODataannotation without having a DTO defined, which would result in a runtime exception. In cases like these, a configuration error is now raised during startup.References: litestar-org/litestar#2779, litestar-org/litestar#2789
- Correctly propagate camelCase names on OpenAPI schema#
 Fix a bug where OpenAPI schema fields would be inappropriately propagated as camelCase where they should have been snake_case
References: litestar-org/litestar#2800
- Fix error handling in event handler stream#
 Fix a class of errors that could result in the event listener stream being terminated when an exception occurred within an event listener. Errors in event listeners are now not propagated anymore but handled by the backend and logged instead.
References: litestar-org/litestar#2810,, litestar-org/litestar#2814
- Fix OpenAPI schema for Pydantic computed fields#
 Add support for including computed fields in schemas generated from Pydantic models.
References: litestar-org/litestar#2792, litestar-org/litestar#2797
2.4.1#
Released: 2023/11/28Bugfixes#
- Fix circular import when importing from 
litestar.security.jwt# An
ImportErrorwas raised when trying to import fromlitestar.security.jwt. This was fixed by removing the imports from the deprecatedlitestar.contrib.jwtwithinlitesetar.security.jwt.References: litestar-org/litestar#2782, litestar-org/litestar#2784
- Raise config error when generator dependencies are cached#
 Previously, an
InternalServerErrorwas raised when attempting to use use_cache=True with generator dependencies. This will now raise a configuration error during application startup.References: litestar-org/litestar#2771, litestar-org/litestar#2780
2.4.0#
Released: 2023/11/27Features#
- Add 
server_lifespanhook# A new
server_lifespanhook is now available onLitestar. This hook works similar to the regularlifespancontext manager, with the difference being is that it is only called once for the entire server lifespan, not for each application startup phase. Note that these only differ when running with an ASGI server that’s using multiple worker processes.References: litestar-org/litestar#2658
- Allow rendering templates directly from strings#
 A new
template_stringparameter was added toTemplate, allowing to render templates directly from strings.See also
References: litestar-org/litestar#2687, litestar-org/litestar#2689
- Support nested DTO field renaming#
 Using similar semantics as for exclusion/inclusion, nested DTO fields can now also be renamed:
from dataclasses import dataclass @dataclass class Bar: id: str @dataclass class Foo: id: str bars: list[Bar] FooDTO = DataclassDTO[Annotated[Foo, DTOConfig(rename_fields={"bars.0.id": "bar_id"})]]
References: litestar-org/litestar#2721, litestar-org/litestar#2764
Bugfixes#
- Fix 
HTTPExceptionhandling during concurrent dependency resolving# An issue was fixed that would lead to
HTTPExceptionsnot being re-raised properly when they occurred within the resolution of nested dependencies during the request lifecycle.References: litestar-org/litestar#2594, litestar-org/litestar#2596
- Fix OpenAPI examples format#
 Fix the OpenAPI examples format by removing the wrapping object.
Before the change, for a given model
@dataclass class Foo: foo: int
The following example would be generated:
{ "description": "Example value", "value": { "foo": 7906 } }
After the fix, this is now:
{ "foo": 7906 }
References: litestar-org/litestar#2272, litestar-org/litestar#2660
- Fix CLI plugin commands not showing up in command list#
 Fix a bug where commands registered by CLI plugins were available, but would not show up in the commands list
References: litestar-org/litestar#2441
- Fix missing 
write-onlymark indto_field()signature# Fix the missing
write-onlystring literal in themarkparameter ofdto_field()References: litestar-org/litestar#2684
- Fix OpenAPI schemas incorrectly flagged as duplicates#
 Fix an issue that would lead to OpenAPI schemas being incorrectly considered duplicates, resulting in an
ImproperlyConfiguredExceptionbeing raised.References: litestar-org/litestar#2471, litestar-org/litestar#2475
- Fix Pydantic URL type support in OpenAPI and serialization#
 Add missing support for Pydantic’s URL types (
AnyUrland its descendants) for both serialization and OpenAPI schema generation. These types were only partially supported previously; Serialization support was lacking for v1 and v2, and OpenAPI support was missing for v2.References: litestar-org/litestar#2664, litestar-org/litestar#2701
- Fix incorrect 
ValidationExceptionmessage when multiple errors were encountered# Fix a bug where
ValidationExceptioncould contain duplicated messages inextrafield, when multiple errors were encountered during validationReferences: litestar-org/litestar#2714, litestar-org/litestar#2716
- Fix DTO renaming renames all fields of the same name in nested DTOs#
 Fix an issue with nested field renaming in DTOs that would lead to all fields with a given name to be renamed in a nested structure.
In the below example, both
Foo.idandBar.idwould have been renamed tofoo_idfrom dataclasses import dataclass @dataclass class Bar: id: str @dataclass class Foo: id: str bar: Bar FooDTO = DataclassDTO[Annotated[Foo, DTOConfig(rename_fields={"id": "foo_id"})]]
References: litestar-org/litestar#2721, litestar-org/litestar#2764
- Fix handling of DTO objects nested in mappings#
 Fix a bug where DTOs nested in a
Mappingtype would fail to serialize correctly.References: litestar-org/litestar#2737, litestar-org/litestar#2775
- Fix inconsistent sequence union parameter errors#
 Fix a bug where unions of collection types would result in different errors depending on whether the union included
Noneor not.References: litestar-org/litestar#2600, litestar-org/litestar#2776
- Fix graceful handling of WebSocket disconnect in channels WebSockets handlers#
 Fix the behaviour of WebSocket disconnect handling within the WebSocket handlers provided by channels, that would sometimes lead to a
RuntimeError: Unexpected ASGI message 'websocket.close', after sending 'websocket.close'.exception being raised upon the closing of a WebSocket connection.References: litestar-org/litestar#2691
2.3.2#
Released: 2023/11/06Bugfixes#
- Fix recursion error when re-using the path of a route handler for static files#
 A regression was fixed that would cause a recursion error when the path of a static files host was reused for a route handler with a different HTTP method.
from litestar import Litestar from litestar import post from litestar.static_files import StaticFilesConfig @post("/uploads") async def handler() -> None: pass app = Litestar( [handler], static_files_config=[ StaticFilesConfig(directories=["uploads"], path="/uploads"), ], )
References: litestar-org/litestar#2629, litestar-org/litestar#2630
2.3.1#
Released: 2023/11/04Bugfixes#
- CLI: Fix not providing SSL certfiles breaks uvicorn command when using reload or multiple workers#
 Fix an issue where not providing the
--ssl-certfileand--ssl-keyfileoptions to thelitestar runcommand would cause aFileNotFoundErrorin uvicorn, when used together with the--reload,--web-concurrencyoptions.References: litestar-org/litestar#2613, litestar-org/litestar#2616
2.3.0#
Released: 2023/11/02Features#
- Python 3.12 support#
 Python 3.12 is now fully supported and tested.
References: litestar-org/litestar#1862, litestar-org/litestar#2396
- New layered parameter 
signature_types# Types in this collection are added to
signature_namespaceusing the type’s__name__attribute. This provides a nicer interface when adding names to the signature namespace w ithout modifying the type name, e.g.:signature_namespace={"Model": Model}is equivalent tosignature_types=[Model].The implementation makes it an error to supply a type in
signature_typesthat has a value for__name__already in the signature namespace.It will also throw an error if an item in
signature_typeshas no__name__attribute.References: litestar-org/litestar#2422
- Added RapiDoc for OpenAPI schema visualisation#
 Add support for using RapiDoc for OpenAPI schema visualisation.
References: litestar-org/litestar#2522
- Support Pydantic 1 & 2 within the same application#
 Added support for Pydantic 1 & 2 within the same application by integrating with Pydantic’s backwards compatibility layer:
from litestar import get from pydantic.v1 import BaseModel as BaseModelV1 from pydantic import BaseModel class V1Foo(BaseModelV1): bar: str class V2Foo(BaseModel): bar: str @get("/1") def foo_v1(data: V1Foo) -> V1Foo: return data @get("/2") def foo_v2(data: V2Foo) -> V2Foo: return data
References: litestar-org/litestar#2487
- Add 
ResponseCacheConfig.cache_response_filterto allow filtering responses eligible for caching# ResponseCacheConfig.cache_response_filteris predicate called by the response cache middleware that discriminates whether a response should be cached, or not.References: litestar-org/litestar#2501, litestar-org/litestar#2537
- SSL support and self-signed certificates for CLI#
 Add support for SSL and generating self-signed certificates to the CLI.
For this, three new arguments were added to the CLI’s
runcommand:--ssl-certfile--ssl-keyfile--create-self-signed-cert
The
--ssl-certfileand –ssl-keyfile flags are passed to uvicorn when usinglitestar run. Uvicorn requires both to be passed (or neither) but additional validation was added to generate a more user friendly CLI errors.The other SSL-related flags (like password or CA) were not added (yet). See uvicorn CLI docs
Generating of a self-signed certificate
One more CLI flag was added (
--create-devcert) that uses thecryptographymodule to generate a self-signed development certificate. Both of the previous flags must be passed when using this flag. Then the following logic is used:If both files already exists, they are used and nothing is generated
If neither file exists, the dev cert and key are generated
If only one file exists, it is ambiguous what to do so an exception is raised
References: litestar-org/litestar#2335, litestar-org/litestar#2554
Bugfixes#
- Use custom request class when given during exception handling#
 When a custom
request_classis provided, it will now be used while returning an error responseReferences: litestar-org/litestar#2399, litestar-org/litestar#2444
- Fix missing OpenAPI schema for generic response type annotations#
 OpenAPI schemas are now correctly generated when a response type annotation contains a generic type such as
from msgspec import Struct from litestar import get, Response from typing import TypeVar, Generic, Optional T = TypeVar("T") class ResponseStruct(Struct, Generic[T]): code: int data: Optional[T] @get("/") def test_handler() -> Response[ResponseStruct[str]]: return Response( ResponseStruct(code=200, data="Hello World"), )
from msgspec import Struct from litestar import get, Response from typing import TypeVar, Generic T = TypeVar("T") class ResponseStruct(Struct, Generic[T]): code: int data: T | None @get("/") def test_handler() -> Response[ResponseStruct[str]]: return Response( ResponseStruct(code=200, data="Hello World"), )
References: litestar-org/litestar#2383, litestar-org/litestar#2463
- Fix rendering of OpenAPI examples#
 An issue was fixed where OpenAPI examples would be rendered as
{ "parameters": [ { "schema": { "type": "string", "examples": [ { "summary": "example summary", "value": "example value" } ] } } ] }
instead of
{ "parameters": [ { "schema": { "type": "string" }, "examples": { "example1": { "summary": "example summary" "value": "example value" } } } ] }
References: litestar-org/litestar#2494, litestar-org/litestar#2509
- Fix non UTF-8 handling when logging requests#
 When structlog is not installed, the request body would not get parsed and shown as a byte sequence. Instead, it was serialized into a string with the assumption that it is valid UTF-8. This was fixed by decoding the bytes with
backslashreplacebefore displaying them.References: litestar-org/litestar#2529, litestar-org/litestar#2530
- Fix 
ExceptionHandlertyping to properly supportExceptionsubclasses# Fix the typing for
ExceptionHandlerto support subclasses ofException, such that code like this will type check properly:from litestar import Request, Response class CustomException(Exception): ... def handle_exc(req: Request, exc: CustomException) -> Response: ...
References: litestar-org/litestar#2520, litestar-org/litestar#2533
- Fix OpenAPI schema generation for variable length tuples#
 Fix a bug where an annotation such as
tuple[str, ...]would cause aTypeError: '<' not supported between instances of 'NoneType' and 'OpenAPIType').References: litestar-org/litestar#2460, litestar-org/litestar#2552
- Fix channels performance issue when polling with no subscribers in 
arbitrary_channels_allowedmode# Fix a bug that would cause high CPU loads while idling when using a
ChannelsPluginwith thearbitrary_channels_allowedenabled and while no subscriptions for any channel were active.References: litestar-org/litestar#2547
- Fix CLI schema export for non-serializable types when using 
create_examples=True# When trying to export a schema via the
litestar schema openapi --output schema.jsonmaking use of a non-JSON serializable type, would result in an encoding error because the standard library JSON serializer was used. This has been fixed by using Litestar’s own JSON encoder, enabling the serialization of all types supplied by the schema.References: litestar-org/litestar#2575, litestar-org/litestar#2581
- Fix OpenAPI schema generation for 
LiteralandEnumunions withNone# Existing behavior was to make the schema for every type that is a union with
Nonea"one_of"schema, that includesOpenAPIType.NULLin the"one_of"types.When a
LiteralorEnumtype is in a union withNone, this behavior is not desirable, as we want to havenullavailable in the list of available options on the type’s schema.This was fixed by modifying
LiteralandEnumschema generation so that i t can be identified that the types are in a union withNone, allowingnullto be included inSchema.enumvalues.References: litestar-org/litestar#2546, litestar-org/litestar#2550
- Fix cache overrides when using same route with different handlers#
 A bug was fixed that would cause the cache for routes being overwritten by a route handler on that same route with a different HTTP method.
References: litestar-org/litestar#2573,, litestar-org/litestar#2588, litestar-org/litestar#2592
2.2.0#
Released: 2023/10/12Features#
- CLI enabled by default#
 The CLI and all its dependencies are now included by default, to enable a better and more consistent developer experience out of the box.
The previous
litestar[cli]extra is still available for backwards compatibility, but as of2.2.0it is without effect.References: litestar-org/litestar#2318, litestar-org/litestar#2346
- Customization of Pydantic integration via 
PydanticPlugin# A new
PydanticPluginhas been added, which can be used to configure Pydantic behaviour. Currently it supports setting aprefer_aliasoption, which will pass theby_alias=Trueflag to Pydantic when exporting models, as well as generate schemas accordingly.References: litestar-org/litestar#2373, litestar-org/litestar#2404
- Add 
/schema/openapi.ymlto the available schema paths# The YAML version of the OpenAPI schema is now available under
/schema/openapi.ymlin addition to/schema/openapi.yaml.References: litestar-org/litestar#2411
- Add experimental DTO codegen backend#
 A new DTO backend was introduced which speeds up the transfer process by generating optimized Python code ahead of time. Testing shows that the new backend is between 2.5 and 5 times faster depending on the operation and data provided.
The new backend can be enabled globally for all DTOs by passing the appropriate feature flag to the Litestar application:
from litestar import Litestar from litestar.config.app import ExperimentalFeatures app = Litestar(experimental_features=[ExperimentalFeatures.DTO_CODEGEN])
See also
For more information see Improving performance with the codegen backend
References: litestar-org/litestar#2388
- Improved error messages for missing required parameters#
 Error messages for missing required parameters will now also contain the source of the expected parameter:
Before:
{ "status_code": 400, "detail": "Missing required parameter foo for url http://testerver.local" }
After:
{ "status_code": 400, "detail": "Missing required header parameter 'foo' for url http://testerver.local" }
References: litestar-org/litestar#2418
Bugfixes#
- Fix implicit conversion of objects to 
boolin debug response# The exception handler middleware would, when in debug mode, implicitly call an object’s
__bool__, which would lead to errors if that object overloaded the operator, for example if the object in question was a SQLAlchemy element.References: litestar-org/litestar#2381, litestar-org/litestar#2384
- Correctly re-export filters and exceptions from 
advanced-alchemy# Some re-exports of filter and exception types from
advanced-alchemywere missing, causing various issues whenadvanced-alchemywas installed, but Litestar would still use its own version of these classes.References: litestar-org/litestar#2358, litestar-org/litestar#2360
- Re-add 
create_enginemethod to SQLAlchemy configs# The
create_enginemethod was removed in anadvanced-alchemyreleases. This was addresses by re-adding it to the versions provided by Litestar.References: litestar-org/litestar#2382
- Fix 
before_requestmodifies route handler signature# The
before_requestwould modify the return annotation of associated route handlers to conform with its own return type annotation, which would cause issues and unexpected behaviour when that annotation was not compatible with the original one.This was fixed by not having the
before_requesthandler modify the route handler’s signature. Users are now expected to ensure that values returned from abefore_requesthandler conform to the return type annotation of the route handler.References: litestar-org/litestar#2368, litestar-org/litestar#2391
- Ensure compression is applied before caching when using compression middleware#
 A previous limitation was removed that would apply compression from the
CompressionMiddlewareonly after a response was restored from the cache, resulting in unnecessary repeated computation and increased size of the stored response.This was due to caching being handled on the response layer, where a response object would be pickled, restored upon a cache hit and then re-sent, including all middlewares.
The new implementation now instead applies caching on the ASGI level; Individual messages sent to the
sendcallable are cached, and later re-sent. This process ensures that the compression middleware has been applied before, and will be skipped when re-sending a cached response.In addition, this increases performance and reduces storage size even in cases where no compression is applied because the slow and inefficient pickle format can be avoided.
References: litestar-org/litestar#1301, litestar-org/litestar#2393
- Fix implicit JSON parsing of URL encoded data#
 A process was removed where Litestar would implicitly attempt to parse parts of URL encoded data as JSON. This was originally added to provide some performance boosts when that data was in fact meant to be JSON, but turned out to be too fragile.
Regular data conversion / validation is unaffected by this.
References: litestar-org/litestar#2394
2.1.1#
Released: 2023/09/24Bugfixes#
- Fix 
DeprecationWarningraised byResponse.to_asgi_response# to_asgi_response()was passing a non-Nonedefault value ([]) toASGIResponseforencoded_headers, resulting in aDeprecationWarningbeing raised. This was fixed by leaving the default value asNone.References: litestar-org/litestar#2364
2.1.0#
Released: 2023/09/23Features#
- Make 
302the defaultstatus_codefor redirect responses# Make
302the defaultstatus_codefor redirect responsesReferences: litestar-org/litestar#2138, litestar-org/litestar#2189
- Add 
include_in_schema()option for all layers# Adds the
include_in_schema()option to all layers, allowing to include/exclude specific routes from the generated OpenAPI schema.References: litestar-org/litestar#2267, litestar-org/litestar#2295
- Deprecate parameter 
appofResponse.to_asgi_response# Adds deprecation warning for unused
appparameter ofto_asgi_responseas it is unused and redundant due torequest.appbeing available.References: litestar-org/litestar#2217, litestar-org/litestar#2268
- Authentication: Add parameters to set the JWT 
extrasfield# Adds
token_extrasto bothBaseJWTAuth.login()andBaseJWTAuth.create_token()methods, to allow the definition of theextrasJWT field.References: litestar-org/litestar#2313
- Templating: Add possibility to customize Jinja environment#
 Adds the ability to pass a custom Jinja2
Environmentor MakoTemplateLookupby providing a dedicated class method.References: litestar-org/litestar#965, litestar-org/litestar#2195
- Add support for minjinja#
 Adds support for MiniJinja, a minimal Jinja2 implementation.
See also
References: litestar-org/litestar#2250
- SQLAlchemy: Exclude implicit fields for SQLAlchemy DTO#
 SQLAlchemyDTO (Advanced Alchemy)can now be configured using a separate config object. This can be set using both class inheritance and Annotated:SQLAlchemyDTO (Advanced Alchemy)can now be configured using a separate config object usingconfigobject.#class MyModelDTO(SQLAlchemyDTO[MyModel]): config = SQLAlchemyDTOConfig()
or
SQLAlchemyDTO (Advanced Alchemy)can now be configured using a separate config object usingAnnotated.#MyModelDTO = SQLAlchemyDTO[Annotated[MyModel, SQLAlchemyDTOConfig()]]
The new configuration currently accepts a single attribute which is
include_implicit_fieldsthat has a default value ofTrue. If set to toFalse, all implicitly mapped columns will be hidden from theDTO. If set tohybrid-only, then hybrid properties will be shown but not other implicit columns.Finally, implicit columns that are marked with
Mark.READ_ONLYorMark.WRITE_ONLYwill always be shown regardless of the value ofinclude_implicit_fields.References: litestar-org/litestar#2170
- SQLAlchemy: Allow repository functions to be filtered by expressions#
 Enhances the SQLALchemy repository so that you can more easily pass in complex
whereexpressions into the repository functions.Tip
Without this, you have to override the
statementparameter and it separates the where conditions from the filters and thekwargs.Allows usage of this syntax:
locations, total_count = await model_service.list_and_count( ST_DWithin(UniqueLocation.location, geog, 1000), account_id=str(account_id) )
instead of the previous method of overriding the
statement:locations, total_count = await model_service.list_and_count( statement=select(Model).where(ST_DWithin(UniqueLocation.location, geog, 1000)), account_id=str(account_id), )
References: litestar-org/litestar#2265
- SQLAlchemy: Use 
lambda_stmtin the repository# Converts the repository to use
lambda_stmtinstead of the normalselectReferences: litestar-org/litestar#2179
- SQLAlchemy: Swap to the advanced_alchemy implementations#
 Swaps the internal SQLAlchemy repository to use the external advanced_alchemy library implementations
References: litestar-org/litestar#2312
Bugfixes#
- Remove usages of deprecated 
ExceptionHandlerMiddlewaredebugparameter# Removes leftover usages of deprecated
ExceptionHandlerMiddlewaredebug parameter.References: litestar-org/litestar#2192
- DTOs: Raise 
ValidationExceptionwhen Pydantic validation fails# Ensures that when the Pydantic validation fails in the Pydantic DTO, a
ValidationExceptionis raised with the extras set to the errors given by Pydantic.References: litestar-org/litestar#2190, litestar-org/litestar#2204
- Set the max width of the console to 80#
 Sets the max width of the console to 80, to prevent the output from being wrapped.
References: litestar-org/litestar#2244
- Handling of optional path parameters#
 Resolves an issue where optional path parameters caused a 500 error to be raised.
References: litestar-org/litestar#2222, litestar-org/litestar#2224
- Use os.replace instead of shutil.move for renaming files#
 Change to using
os.replace()instead ofshutil.move()for renaming files, to ensure atomicity.References: litestar-org/litestar#2223
- Exception detail attribute#
 Set correctly the detail attribute on
LitestarExceptionandHTTPExceptionregardless of whether it’s passed positionally or by name.References: litestar-org/litestar#2231
- Filters not available in 
exists()# Fixes
exists()method for SQLAlchemy sync and async.References: litestar-org/litestar#2221, litestar-org/litestar#2228
- Add Pydantic types to SQLAlchemy registry only if Pydantic is installed#
 Allows importing from
litestar.contrib.sqlalchemy.baseeven if Pydantic is not installed.References: litestar-org/litestar#2252
- Don’t add content type for responses that don’t have a body#
 Ensures that the
content-typeheader is not added for responses that do not have a body such as responses with status code204 (No Content).References: litestar-org/litestar#2106, litestar-org/litestar#2263
SQLAlchemyPluginrefactored#Changes the way the
SQLAlchemyPluginto now append the other plugins instead of the inheritance that was previously used. This makes using theplugins.getfunction work as expected.References: litestar-org/litestar#2269
- Ensure 
app-diris appended to path during autodiscovery# Fixes a bug which caused the
--app-diroption to the Litestar CLI to not be propagated during autodiscovery.References: litestar-org/litestar#2266, litestar-org/litestar#2277
- Set content length header by default#
 Sets the
content-lengthheader by default even if the length of the body is0.References: litestar-org/litestar#2271
- Incorrect handling of mutable headers in 
ASGIResponse# Update
ASGIResponse,Responseand friends to address a few issues related to headers:If
encoded_headerswere passed in at any point, they were mutated within responses, leading to a growing list of headers with every responseWhile mutating
encoded_headers, the checks performed to assert a value was (not) already present, headers were not treated case-insensitiveUnnecessary work was performed while converting cookies / headers into an encoded headers list
This was fixed by:
Removing the use of and deprecate
encoded_headersHandling headers on
ASGIResponsewithMutableScopeHeaders, which allows for case-insensitive membership tests,.setdefaultoperations, etc.
References: litestar-org/litestar#2196, litestar-org/litestar#2308
- Adds missing ORM registry export#
 Adds an export that was overlooked for the base repo
References: litestar-org/litestar#2316
- Discrepancy in 
attrs,msgspecandPydanticfor multi-part forms# Resolves issue in
attrs,msgspecand Pydantic for multi-part formsReferences: litestar-org/litestar#2278, litestar-org/litestar#2280
- Set proper default for 
exclude_http_methodsin auth middleware# Sets
OPTIONSas the default value forexclude_http_methodsin the base authentication middleware class.References: litestar-org/litestar#2205, litestar-org/litestar#2325
2.0.0#
Released: 2023/08/19Bugfixes#
- Regression | Missing 
media_typeinformation to error responses# Fixed a regression that caused error responses to be sent using a mismatched media type, e.g. an error response from a
text/htmlendpoint would be sent as JSON.References: litestar-org/litestar#2024, litestar-org/litestar#2131
- Regression | 
Litestar.debugdoes not propagate to exception handling middleware# Fixed a regression where setting
Litestar.debugwould not propagate to the exception handler middleware, resulting in exception responses always being sent using the initial debug value.References: litestar-org/litestar#2147, litestar-org/litestar#2153
- Static files not being served if a route handler with the same base path was registered#
 Fixed a bug that would result in a
404 - Not Foundwhen requesting a static file where thepathwas also used by a route handler.References: litestar-org/litestar#2154
- HTMX: Missing default values for 
receiveandsendparameters ofHTMXRequest# Add missing default values for the
receiveandsendparameters ofHTMXRequest.References: litestar-org/litestar#2145
- DTO: Excluded attributes accessed during transfer#
 Fix the behaviour of DTOs such that they will no longer access fields that have been included. This behaviour would previously cause issues when these attributes were either costly or impossible to access (e.g. lazy loaded relationships of a SQLAlchemy model).
References: litestar-org/litestar#2125, litestar-org/litestar#2127
- DTO | Regression: 
DTOData.create_instanceignores renaming# Fix a regression where calling
create_instance()would ignore the renaming settings of fields.References: litestar-org/litestar#2144
- OpenAPI | Regression: Response schema for files and streams set 
application/octet-streamascontentEncodinginstead ofcontentMediaType# Fix a regression that would set
application/octet-streamas thecontentEncodinginstead ofcontentMediaTypein the response schema ofFileStream.References: litestar-org/litestar#2130
- OpenAPI | Regression: Response schema diverges from 
prefer_aliassetting for Pydantic models# Fix a regression that made the response schema use
prefer_alias=True, diverging from how Pydantic models are exported by default.References: litestar-org/litestar#2150
- OpenAPI | Regression: Examples not being generated deterministically#
 Fix a regression that made generated examples non-deterministic, caused by a misconfiguration of the random seeding.
References: litestar-org/litestar#2161
- SQLAlchemy repository: Handling of dialects not supporting JSON#
 Fix a bug where SQLAlchemy would raise a
TypeErrorwhen using a dialect that does not support JSON with the SQLAlchemy repositories.References: litestar-org/litestar#2137, litestar-org/litestar#2139
- JWT | Regression: 
OPTIONSandHEADbeing authenticated by default# Fix a regression that would make
litestar.contrib.jwt.JWTAuthenticationMiddlewareauthenticateOPTIONSandHEADrequests by default.References: litestar-org/litestar#2160
- SessionAuth | Regression: 
OPTIONSandHEADbeing authenticated by default# Fix a regression that would make
SessionAuthMiddlewareauthenticateOPTIONSandHEADrequests by default.References: litestar-org/litestar#2182
2.0.0rc1#
Released: 2023/08/05Features#
- Support for server-sent-events#
 Support for Server-sent events <https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events> has been added with the
ServerSentEvent:async def my_generator() -> AsyncGenerator[bytes, None]: count = 0 while count < 10: await sleep(0.01) count += 1 yield str(count) @get(path="/count") def sse_handler() -> ServerSentEvent: return ServerSentEvent(my_generator())
See also
References: litestar-org/litestar#1185, litestar-org/litestar#2035
- SQLAlchemy repository: allow specifying 
id_attributeper method# The following methods now accept an
id_attributeargument, allowing to specify an alternative value to the models primary key:~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.delete~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.delete_many~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.get~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.update~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.delete~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.delete_many~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.get~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.update
References: litestar-org/litestar#2052
- SQLAlchemy repository: New 
upsert_manymethod# A new method
upsert_manyhas been added to the SQLAlchemy repositories, providing equivalent functionality to theupsertmethod for multiple model instances.See also
~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.upsert_many~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.upsert_manyReferences: litestar-org/litestar#2056
- SQLAlchemy repository: New filters: 
OnBeforeAfter,NotInCollectionFilterandNotInSearchFilter# The following filters have been added to the SQLAlchemy repositories:
litestar.contrib.repository.filters.OnBeforeAfterAllowing to filter
datetime.datetimecolumnslitestar.contrib.repository.filters.NotInCollectionFilterAllowing to filter using a
WHERE ... NOT IN (...)clauselitestar.contrib.repository.filters.NotInSearchFilterAllowing to filter using a WHERE field_name NOT LIKE ‘%’ || :value || ‘%’` clause
References: litestar-org/litestar#2057
- SQLAlchemy repository: Configurable chunk sizing for 
delete_many# The repository now accepts a
chunk_sizeparameter, determining the maximum amount of parameters in anINstatement before it gets chunked.This is currently only used in the
delete_manymethod.References: litestar-org/litestar#2061
- SQLAlchemy repository: Support InstrumentedAttribute for attribute columns#
 Support
InstrumentedAttributefor in the repository’sid_attribute, and the following methods:~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.delete~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.delete_many~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.get~litestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.update~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.delete~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.delete_many~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.get~litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository.update
References: litestar-org/litestar#2054
- OpenAPI: Support callable 
operation_idon route handlers# Route handlers may be passed a callable to
operation_idto create the OpenAPI operation ID.References: litestar-org/litestar#2078
- Run event listeners concurrently#
 Events now run concurrently inside a task group.
References: litestar-org/litestar#2096
- Support extending the CLI with plugins#
 A new plugin protocol
CLIPluginProtocolhas been added that can be used to extend the Litestar CLI.See also
References: litestar-org/litestar#2066
Bugfixes#
- DTO: Support renamed fields in 
DTODataandcreate_instance# A bug was fixed that would cause field renaming to be skipped within
DTODataandcreate_instance().References: litestar-org/litestar#2065
- SQLAlchemy repository: Fix 
health_checkfor oracle# The emitted statement for oracle has been changed to
SELECT 1 FROM DUAL.References: litestar-org/litestar#2060
- Fix serialization of empty strings in multipart form#
 A bug was fixed that would cause a validation error to be raised for empty strings during multipart form decoding.
References: litestar-org/litestar#2044
Other changes#
- Use debug mode by default in test clients#
 The test clients will now default to
debug=Trueinstead ofdebug=None.References: litestar-org/litestar#2113
- Removal of deprecated 
partialmodule#breaking The deprecated
litestar.partialhas been removed. It can be replaced with DTOs, making use of theDTOConfigoptionpartial=True.References: litestar-org/litestar#2113
- Removal of deprecated 
dto/factorymodule#breaking The deprecated module
litestar.dto.factoryhas been removed.References: litestar-org/litestar#2114
- Removal of deprecated 
contrib/msgspecmodule#breaking The deprecated module
litestar.contrib.msgspechas been removed.References: litestar-org/litestar#2114
2.0.0beta4#
Released: 2023/07/21Bugfixes#
- Fix extra package dependencies#
 A workaround for a bug in poetry that caused development / extra dependencies to be installed alongside the package has been added.
References: litestar-org/litestar#2029
2.0.0beta3#
Released: 2023/07/20Features#
SQLAlchemyDTO (Advanced Alchemy): column/relationship type inference#If type annotations aren’t available for a given column/relationship, they may be inferred from the mapped object.
For columns, the
type‘spython_typewill be used as the type of the column, and thenullableproperty to determine if the field should have aNoneunion.For relationships, where the
RelationshipProperty.directionisONETOMANYorMANYTOMANY,RelationshipProperty.collection_classandRelationshipProperty.mapper.class_are used to construct an annotation for the collection.For one-to-one relationships,
RelationshipProperty.mapper.class_is used to get the type annotation, and will be made a union withNoneif all of the foreign key columns are nullable.References: litestar-org/litestar#1853, litestar-org/litestar#1879
- DTO: Piccolo ORM#
 Add support for piccolo ORM with the
PiccoloDTO.References: litestar-org/litestar#1896
- OpenAPI: Allow setting 
OpenAPIController.pathfrom`OpenAPIConfig# pathhas been added, which can be used to set thepathforOpenAPIControllerdirectly, without needing to create a custom instance of it.If
pathis set in bothOpenAPIConfigandOpenAPIController, the path set on the controller will take precedence.References: litestar-org/litestar#1886
- SQLAlchemy repository: 
auto_commit,auto_expungeandauto_refreshoptions# Three new parameters have been added to the repository and various methods:
auto_commitWhen this
True, the session willcommit()instead offlush()before returning.Available in:
~SQLAlchemyAsyncRepository.add~SQLAlchemyAsyncRepository.add_many~SQLAlchemyAsyncRepository.delete~SQLAlchemyAsyncRepository.delete_many~SQLAlchemyAsyncRepository.get_or_create~SQLAlchemyAsyncRepository.update~SQLAlchemyAsyncRepository.update_many~SQLAlchemyAsyncRepository.upsert
(and their sync equivalents)
auto_refreshWhen
True, the session will executerefresh()objects before returning.Available in:
~SQLAlchemyAsyncRepository.add~SQLAlchemyAsyncRepository.get_or_create~SQLAlchemyAsyncRepository.update~SQLAlchemyAsyncRepository.upsert
(and their sync equivalents)
auto_expungeWhen this is
True, the session will executeexpunge()all objects before returning.Available in:
~SQLAlchemyAsyncRepository.add~SQLAlchemyAsyncRepository.add_many~SQLAlchemyAsyncRepository.delete~SQLAlchemyAsyncRepository.delete_many~SQLAlchemyAsyncRepository.get~SQLAlchemyAsyncRepository.get_one~SQLAlchemyAsyncRepository.get_one_or_none~SQLAlchemyAsyncRepository.get_or_create~SQLAlchemyAsyncRepository.update~SQLAlchemyAsyncRepository.update_many~SQLAlchemyAsyncRepository.list~SQLAlchemyAsyncRepository.upsert
(and their sync equivalents)
References: litestar-org/litestar#1900
- Include path name in 
ImproperlyConfiguredExceptionmessage for missing param types# The message of a
ImproperlyConfiguredExceptionraised when a path parameter is missing a type now contains the name of the path.References: litestar-org/litestar#1935
- DTO: New 
includeparameter added toDTOConfig# includehas been added toDTOConfig, providing a counterpart toexclude.If
includeis provided, only those fields specified within it will be included.References: litestar-org/litestar#1950
- Pydantic 2 support#
 Pydantic 2 is now supported alongside Pydantic 1.
References: litestar-org/litestar#1956
Bugfixes#
- SQLAlchemy repository: Fix audit columns defaulting to app startup time#
 A bug was fixed where
~litestar.contrib.sqlalchemy.base.AuditColumns.created_atand~litestar.contrib.sqlalchemy.base.AuditColumns.updated_atwould default to thedatetimeat initialization time, instead of the time of the update.References: litestar-org/litestar#1894
SQLAlchemyDTO (Advanced Alchemy): Fix handling ofSequencewith defaults#Fixes handling of columns defined with Sequence default values.
The SQLAlchemy default value for a
Columnwill be ignored when it is aSequenceobject. This is because the SQLAlchemy sequence types represent server generated values, and there is no way for us to generate a reasonable default value for that field from it without making a database query, which is not possible deserialization.References: litestar-org/litestar#1851, litestar-org/litestar#1883
- Allow JSON as redirect response#
 Enables using redirect responses with a JSON media type.
References: litestar-org/litestar#1908
- DTO / OpenAPI: Fix detection of required fields for Pydantic and msgspec DTOs#
 A bug was fixed that would lead to fields of a Pydantic model or msgspec Structs being marked as “not required” in the generated OpenAPI schema when used with DTOs.
References: litestar-org/litestar#1946
Other changes#
AbstractDTOFactorymoved todto.factory.base#breakingAbstractDTOFactoryhas moved fromlitestar.dto.factory.abctolitestar.dto.factory.base.References: litestar-org/litestar#1950
- SQLAlchemy repository: Rename 
_sentinelcolumn tosa_orm_sentinel#breaking The
_sentinelcolumn of~litestar.contrib.sqlalchemy.base.UUIDPrimaryKeyhas been renamed tosa_orm_sentinel, to support Spanner, which does not support tables starting with_.References: litestar-org/litestar#1933
- Replace 
Header,CacheControlHeaderandETagPydantic models with dataclasses#breaking As part of the removal of Pydantic as a hard dependency, the header models
Header,CacheControlHeaderandETaghave been replaced with dataclasses.Note
Although marked breaking, this change should not affect usage unless you relied on these being Pydantic models in some way.
References: litestar-org/litestar#1917
- Pydantic as an optional dependency#breaking
 As of this release, Pydantic is no longer a required dependency of Litestar. It is still supported in the same capacity as before, but Litestar itself does not depend on it anymore in its internals.
References: litestar-org/litestar#1963
- Deprecation of  
partialmodule# The
litestar.partialandlitestar.partial.Partialhave been deprecated and will be removed in a future release. Users are advised to upgrade to DTOs, making use of theDTOConfigoptionpartial=True.References: litestar-org/litestar#2002
2.0.0beta2#
Released: 2023/06/24Features#
- Support 
annotated-types# Extended support for the annotated-types library is now available.
References: litestar-org/litestar#1847
- Increased verbosity of validation error response keys#breaking
 The keys in validation error responses now include the full path to the field where the originated.
An optional
sourcekey has been added, signifying whether the value is from the body, a cookie, a header, or a query param.before#{ "status_code": 400, "detail": "Validation failed for POST http://localhost:8000/some-route", "extra": [ {"key": "int_param", "message": "value is not a valid integer"}, {"key": "int_header", "message": "value is not a valid integer"}, {"key": "int_cookie", "message": "value is not a valid integer"}, {"key": "my_value", "message": "value is not a valid integer"} ] }
after#{ "status_code": 400, "detail": "Validation failed for POST http://localhost:8000/some-route", "extra": [ {"key": "child.my_value", "message": "value is not a valid integer", "source": "body"}, {"key": "int_param", "message": "value is not a valid integer", "source": "query"}, {"key": "int_header", "message": "value is not a valid integer", "source": "header"}, {"key": "int_cookie", "message": "value is not a valid integer", "source": "cookie"}, ] }
References: litestar-org/litestar#1774
TestClientdefault timeout#breakingA
timeoutparameter was added toThe value is passed down to the underlying HTTPX client and serves as a default timeout for all requests.
References: litestar-org/litestar#1840
- SQLAlchemy DTO: Explicit error messages when type annotations for a column are missing#
 Replace the nondescript
KeyErrorraised when a SQLAlchemy DTO is constructed from a model that is missing a type annotation for an included column with anImproperlyConfiguredException, including an explicit error message, pointing at the potential cause.References: litestar-org/litestar#1852
Bugfixes#
- Remove exception details from Internal Server Error responses#
 Error responses with a
500status code will now always use “Internal Server Error” as default detail.References: litestar-org/litestar#1856, litestar-org/litestar#1857
- Pydantic v1 regex validation#
 A regression has been fixed in the Pydantic signature model logic, which was caused by the renaming of
regextopattern, which would lead to thepatternnot being validated.References: litestar-org/litestar#1860, litestar-org/litestar#1865
2.0.0beta1#
Released: 2023/06/16Features#
- Expose 
ParsedTypeas public API# Expose the previously private
litestar.typing.ParsedType. This is mainly indented for usage withlitestar.plugins.SerializationPluginProtocol.supports_type()References: litestar-org/litestar#1677, litestar-org/litestar#1567
- Improved debugging capabilities#
 A new
pdb_on_exceptionparameter was added toLitestar. When set toTrue, Litestar will drop into a the Python debugger when an exception occurs. It defaults toNoneWhen
pdb_on_exceptionisNone, setting the environment variableLITESTAR_PDB=1can be used to enable this behaviourWhen using the CLI, passing the
--pdbflag to theruncommand will temporarily set the environment variableLITESTAR_PDB=1
References: litestar-org/litestar#1742
- OpenAPI: Add operation_class argument to HTTP route handlers#
 The
operation_classargument was added toHTTPRouteHandlerand the corresponding decorators, allowing to override theOperationclass, to enable further customization of the generated OpenAPI schema.References: litestar-org/litestar#1732
- OpenAPI: Support nested 
Literalannotations# Support nested
typing.Literalannotations by flattening them into a singleLiteral.References: litestar-org/litestar#1829
- CLI: Add 
--reload-diroption toruncommand# A new
--reload-diroption was added to thelitestar runcommand. When used,--reloadis implied, and the server will watch for changes in the given directory.References: litestar-org/litestar#1689
- Allow extra attributes on JWTs via 
extrasattribute# Add the
litestar.contrib.jwt.Token.extrasattribute, containing extra attributes found on the JWT.References: litestar-org/litestar#1695
- Add default modes for 
Websocket.iter_jsonandWebSocket.iter_data# Add a default
modeforiter_json()anditer_data(), with a value oftext.References: litestar-org/litestar#1733
- SQLAlchemy repository: Synchronous repositories#
 Add a new synchronous repository base class:
litestar.contrib.sqlalchemy.repository.SQLAlchemySyncRepository, which offer the same functionality as its asynchronous counterpart while operating on a synchronoussqlalchemy.orm.Session.References: litestar-org/litestar#1683
- SQLAlchemy repository: Oracle Database support#
 Add support for Oracle Database via oracledb.
References: litestar-org/litestar#1694
- SQLAlchemy repository: DuckDB support#
 Add support for DuckDB.
References: litestar-org/litestar#1744
- SQLAlchemy repository: Google Spanner support#
 Add support for Google Spanner.
References: litestar-org/litestar#1744
- SQLAlchemy repository: JSON check constraint for Oracle Database#
 When using the
litestar.contrib.sqlalchemy.types.JsonBtype with an Oracle Database engine, a JSON check constraint will be created for that column.References: litestar-org/litestar#1780
- SQLAlchemy repository: Remove 
createdandupdatedcolumns#breaking The
createdandupdatedcolumns have been superseded bycreated_atandupdated_atrespectively, to prevent name clashes.References: litestar-org/litestar#1816
- SQLAlchemy repository: Add timezone aware type#breaking
 A new timezone aware type
litestar.contrib.sqlalchemy.types.DateTimeUTChas been added, which enforces UTC timestamps stored in the database.References: litestar-org/litestar#1816
- SQLAlchemy repository: Exclude unloaded columns in 
to_dict# When exporting models using the
~litestar.contrib.sqlalchemy.base.CommonTableAttributes.to_dictmethod, unloaded columns will now always be excluded. This prevents implicit I/O via lazy loading, and errors when using an asynchronous session.References: litestar-org/litestar#1802
- DTOs: Nested keyword arguments in 
.create_instance()# The
DTOData.create_instancemethod now supports providing values for arbitrarily nested data via kwargs using a double-underscore syntax, for exampledata.create_instance(foo__bar="baz").See also
References: litestar-org/litestar#1727, litestar-org/litestar#1741
- DTOs: Hybrid properties and association proxies in
SQLAlchemyDTO (Advanced Alchemy)# The
SQLAlchemyDTO (Advanced Alchemy)now supports hybrid attribute and associationproxy.The generated field will be marked read-only.
References: litestar-org/litestar#1754, litestar-org/litestar#1776
- DTOs: Transfer to generic collection types#
 DTOs can now be wrapped in generic collection types such as
typing.Sequence. These will be substituted with a concrete and instantiable type at run time, e.g. in the case ofSequencealist.References: litestar-org/litestar#1763, litestar-org/litestar#1764
- DTOs: Data transfer for non-generic builtin collection annotations#
 Non-parametrized generics in annotations (e.g.
a: dict) will now be inferred as being parametrized withAny.a: dictis then equivalent toa: dict[Any, Any].References: litestar-org/litestar#1799
- DTOs: Exclude leading underscore fields by default#breaking
 Leading underscore fields will not be excluded by default. This behaviour can be configured with the newly introduced
underscore_fields_privateconfiguration value, which defaults toTrue.References: litestar-org/litestar#1768, litestar-org/litestar#1777
- DTOs: Msgspec and Pydantic DTO factory implementation#
 DTO factories for msgspec and Pydantic have been added:
MsgspecDTOPydanticDTO
References: litestar-org/litestar#1531,, litestar-org/litestar#1532, litestar-org/litestar#1712
Bugfixes#
- Store and reuse state deep_copy directive when copying state#
 App state can be created using
deep_copy=False, however state would still be deep copied for dependency injection.This was fixed memoizing the value of
deep_copywhen state is created, and reusing it on subsequent copies.References: litestar-org/litestar#1674, litestar-org/litestar#1678
ParsedType.is_subclass_of(X)Truefor union if all union types are subtypes ofX#When
ParsedTypewas introduced,is_subclass_of()any union was deliberately left to returnFalsewith the intention of waiting for some use-cases to arrive.This behaviour was changed to address an issue where a handler may be typed to return a union of multiple response types; If all response types are
Responsesubtypes then the correct response handler will now be applied.References: litestar-org/litestar#1652, litestar-org/litestar#1690
- Inconsistent template autoescape behavior#
 The mako template engine now defaults to autoescaping expressions, making it consistent with config of Jinja template engine.
References: litestar-org/litestar#1699, litestar-org/litestar#1718
- Missing 
ChannelsPluginin signature namespace population# The
ChannelsPluginhas been added to the signature namespace, fixing an issue where usingfrom __future__ import annotationsor stringized annotations would lead to aNameError, if the plugin was not added to the signatured namespace manually.References: litestar-org/litestar#1691, litestar-org/litestar#1719
- Gzip middleware not sending small streaming responses#
 A bug was fixed that would cause smaller streaming responses to not be sent at all when the
CompressionMiddlewarewas used withgzip.References: litestar-org/litestar#1681, litestar-org/litestar#1723
- Premature transfer to nested models with DTOData#
 An issue was fixed where data that should be transferred to builtin types on instantiation of
DTODatawas being instantiated into a model type for nested models.References: litestar-org/litestar#1726, litestar-org/litestar#1731
- Incorrect 
sync_to_threadusage warnings for generator dependencies# A bug was fixed that caused incorrect warnings about missing
sync_to_threadusage were issues when asynchronous generators were being used as dependencies.References: litestar-org/litestar#1711, litestar-org/litestar#1716, litestar-org/litestar#1740
- Dependency injection custom dependencies in 
WebSocketListener# An issue was resolved that would cause failures when dependency injection was being used with custom dependencies (that is, injection of things other than
state,query, path parameters, etc.) within aWebsocketListener.References: litestar-org/litestar#1762, litestar-org/litestar#1807
- OpenAPI schema for 
Dict[K, V]ignores generic# An issue with the OpenAPI schema generation was fixed that would lead to generic arguments to
dictbeing ignored.An type like
dict[str, int]now correctly renders as{"type": "object", "additionalProperties": { "type": "integer" }}.References: litestar-org/litestar#1795, litestar-org/litestar#1828
WebSocketTestSessionnot timing out without when connection is not accepted#A bug was fixed that caused
WebSocketTestSessionto block indefinitely when ifaccept()was never called, ignoring thetimeoutparameter.References: litestar-org/litestar#1696
- SQLAlchemy repository: Fix alembic migrations generated for models using 
GUID# Migrations generated for models with a
~litestar.contrib.sqlalchemy.types.GUIDtype would erroneously add alength=16on the input. Since this parameter is not defined in the type’s the__init__method. This was fixed by adding the appropriate parameter to the type’s signature.References: litestar-org/litestar#1676
Other changes#
- DTOs: Arbitrary generic wrappers#
 When a handler returns a type that is not supported by the DTO, but:
the return type is generic
it has a generic type argument that is supported by the dto
the type argument maps to an attribute on the return type
the DTO operations will be performed on the data retrieved from that attribute of the instance returned from the handler, and return the instance.
The constraints are:
the type returned from the handler must be a type that litestar can natively encode
the annotation of the attribute that holds the data must be a type that DTOs can otherwise manage
from dataclasses import dataclass from typing import Generic, List, TypeVar from typing_extensions import Annotated from litestar import Litestar, get from litestar.dto import DTOConfig from litestar.dto.factory.dataclass_factory import DataclassDTO @dataclass class User: name: str age: int T = TypeVar("T") V = TypeVar("V") @dataclass class Wrapped(Generic[T, V]): data: List[T] other: V @get(dto=DataclassDTO[Annotated[User, DTOConfig(exclude={"age"})]]) def handler() -> Wrapped[User, int]: return Wrapped( data=[User(name="John", age=42), User(name="Jane", age=43)], other=2, ) app = Litestar(route_handlers=[handler]) # GET "/": {"data": [{"name": "John"}, {"name": "Jane"}], "other": 2}
from dataclasses import dataclass from typing import Generic, TypeVar from typing import Annotated from litestar import Litestar, get from litestar.dto import DTOConfig from litestar.dto.factory.dataclass_factory import DataclassDTO @dataclass class User: name: str age: int T = TypeVar("T") V = TypeVar("V") @dataclass class Wrapped(Generic[T, V]): data: list[T] other: V @get(dto=DataclassDTO[Annotated[User, DTOConfig(exclude={"age"})]]) def handler() -> Wrapped[User, int]: return Wrapped( data=[User(name="John", age=42), User(name="Jane", age=43)], other=2, ) app = Litestar(route_handlers=[handler]) # GET "/": {"data": [{"name": "John"}, {"name": "Jane"}], "other": 2}
References: litestar-org/litestar#1631,, litestar-org/litestar#1798, litestar-org/litestar#1801
- Remove 
stateparameter fromAfterExceptionHookHandlerandBeforeMessageSendHookHandler#breaking Remove the
stateparameter fromAfterExceptionHookHandlerandBeforeMessageSendHookHandler.AfterExceptionHookHandlers will have to be updated fromasync def after_exception_handler( exc: Exception, scope: Scope, state: State ) -> None: ...
to
async def after_exception_handler(exc: Exception, scope: Scope) -> None: ...
The state can still be accessed like so:
async def after_exception_handler(exc: Exception, scope: Scope) -> None: state = scope["app"].state
BeforeMessageSendHookHandlers will have to be updated fromasync def before_send_hook_handler( message: Message, state: State, scope: Scope ) -> None: ...
to
async def before_send_hook_handler(message: Message, scope: Scope) -> None: ...
where state can be accessed in the same manner:
async def before_send_hook_handler(message: Message, scope: Scope) -> None: state = scope["app"].state
References: litestar-org/litestar#1739
- Removal of 
dto.exceptionsmodule#breaking The module
dto.exceptionshas been removed, since it was not used anymore internally by the DTO implementations, and superseded by standard exceptions.References: litestar-org/litestar#1773
BaseRouteHandlerno longer generic#breakingBaseRouteHandlerwas originally made generic to support proper typing of theownership_layersproperty, but the same effect can now be achieved usingtyping.Self.References: litestar-org/litestar#1819
- Deprecation of 
Litestarparameterpreferred_validation_backend#breaking The following changes have been made regarding the
preferred_validation_backend:The
preferred_validation_backendparameter ofLitestarhas been renamed to_preferred_validation_backendand deprecated. It will be removed completely in a future version.The
Litestar.preferred_validation_backendattribute has been made privateThe
preferred_validation_backendattribute has been removed fromAppConfig
In addition, the logic for selecting a signature validation backend has been simplified as follows: If the preferred backend is set to
attrs, or the signature contains attrs types,attrsis selected. In all other cases, Pydantic will be used.References: litestar-org/litestar#1810
Response.get_serializermoved toserialization.get_serializer#breakingThe
Response.get_serializer()method has been removed in favor of theget_serializer()function.In the previous
Responseimplementation,get_serializer()was called on the response inside the response’s__init__, and the merging of class-leveltype_encoderswith theResponse‘stype_encodersoccurred inside itsget_serializermethod.In the current version of
Response, the response body is not encoded until after the response object has been returned from the handler, and it is converted into a low-levelASGIResponseobject. Due to this, there is still opportunity for the handler layer resolvedtype_encodersobject to be merged with theResponsedefinedtype_encoders, making the merge inside theResponseno longer necessary.In addition, the separate
get_serializerfunction greatly simplifies the interaction between middlewares and serializers, allowing to retrieve one independently from aResponse.References: litestar-org/litestar#1820
- Remove response containers and introduce 
ASGIResponse#breaking Response Containers were wrapper classes used to indicate the type of response returned by a handler, for example
File,Redirect,TemplateandStreamtypes. These types abstracted the interface of responses from the underlying response itself.Response containers have been removed and their functionality largely merged with that of
Response. The predefined response containers still exist functionally, as subclasses ofResponseand are now located within thelitestar.responsemodule. In addition to the functionality of Response containers, they now also feature all of the response’s functionality, such as methods to add headers and cookies.The
Responseclass now only serves as a wrapper and context object, and does not handle the data sending part, which has been delegated to a newly introducedASGIResponse. This type (and its subclasses) represent the response as an immutable object and are used internally by Litestar to perform the I/O operations of the response. These can be created and returned from handlers like any other ASGI application, however they are low-level, and lack the utility of the higher-level response types.References: litestar-org/litestar#1790
2.0.0alpha7#
Released: 2023/05/14Features#
- Warn about sync callables in route handlers and dependencies without an explicit 
sync_to_threadvalue# A warning will now be raised when a synchronous callable is being used in an
HTTPRouteHandlerorProvide, without settingsync_to_thread. This is to ensure that synchronous callables are handled properly, and to prevent accidentally using callables which might block the main thread.This warning can be turned off globally by setting the environment variable
LITESTAR_WARN_IMPLICIT_SYNC_TO_THREAD=0.See also
References: litestar-org/litestar#1648, litestar-org/litestar#1655
- Warn about 
sync_to_threadwith async callables# A warning will be raised when
sync_to_threadis being used inHTTPRouteHandlerorProvidewith an asynchronous callable, as this will have no effect.This warning can be turned off globally by setting the environment variable
LITESTAR_WARN_SYNC_TO_THREAD_WITH_ASYNC=0.References: litestar-org/litestar#1664
- WebSockets: Dependencies in listener hooks#
 Dependencies can now be used in the
websocket_listenerhookson_accept,on_disconnectand theconnection_lifespancontext manager. Thesocketparameter is therefore also not mandatory anymore in those callables.References: litestar-org/litestar#1647
- Declaring dependencies without 
Provide# Dependencies can now be declared without using
Provide. The callables can be passed directly to thedependenciesdictionary.References: litestar-org/litestar#1647
- Add 
DTODatato receive unstructured but validated DTO data# DTODatais a datastructure for interacting with DTO validated data in its unstructured form.This utility is to support the case where the amount of data that is available from the client request is not complete enough to instantiate an instance of the model that would otherwise be injected.
References: litestar-org/litestar#1650
- Partial DTOs#
 Add a
partialflag toDTOConfig, making all DTO fields options. Subsequently, any unset values will be filtered when extracting data from transfer models.This allows for example to use a to handle PATCH requests more easily.
References: litestar-org/litestar#1651
- SQLAlchemy repository: 
psycopgasyncio support# Async psycopg is now officially supported and tested for the SQLAlchemy repository.
References: litestar-org/litestar#1657
- SQLAlchemy repository: 
BigIntPrimaryKeymixin# ~litestar.contrib.sqlalchemy.base.BigIntPrimaryKeymixin, providing aBigIntprimary key column, with a fallback toIntegerfor sqlite.References: litestar-org/litestar#1657
- SQLAlchemy repository: Store GUIDs as binary on databases that don’t have a native GUID type#
 On databases without native support for GUIDs,
~litestar.contrib.sqlalchemy.types.GUIDwill now fall back toBINARY(16).References: litestar-org/litestar#1657
- Application lifespan context managers#
 A new
lifespanargument has been added toLitestar, accepting an asynchronous context manager, wrapping the lifespan of the application. It will be entered with the startup phase and exited on shutdown, providing functionality equal to theon_startupandon_shutdownhooks.References: litestar-org/litestar#1635
- Unify application lifespan hooks: Remove 
before_andafter_#breaking The following application lifespan hooks have been removed:
before_startupafter_startupbefore_shutdownafter_shutdown
The remaining hooks
on_startupandon_shutdownwill now receive as their optional first argument theLitestarapplication instead of the application’s state.References: litestar-org/litestar#1663
- Trio-compatible event emitter#
 The default
SimpleEventEmitteris now compatible with trio.References: litestar-org/litestar#1666
- OpenAPI: Support 
msgspec.Meta# msgspec.Metais now fully supported for OpenAPI schema generation.References: litestar-org/litestar#1669
- OpenAPI: Support Pydantic 
FieldInfo# Pydantic’s
FieldInfo(regex,gt,title, etc.) now have full support for OpenAPI schema generation.References: litestar-org/litestar#1541, litestar-org/litestar#1670
Bugfixes#
- OpenAPI: Fix name collision in DTO models#
 A bug was fixed that would lead to name collisions in the OpenAPI schema when using DTOs with the same class name. DTOs now include a short 8 byte random string in their generated name to prevent this.
References: litestar-org/litestar#1643, litestar-org/litestar#1649
- Fix validated attrs model being injected as a dictionary#
 A bug was fixed that would lead to an attrs model used to validate a route handler’s
datanot being injected itself but as a dictionary representation.References: litestar-org/litestar#1643, litestar-org/litestar#1668
- Validate unknown media types#breaking
 An unknown media type in places where Litestar can’t infer the type from the return annotation, an
ImproperlyConfiguredExceptionwill now be raised.References: litestar-org/litestar#1446, litestar-org/litestar#1671
2.0.0alpha6#
Released: 2023/05/09Features#
- Add 
connection_accept_handlertowebsocket_listener# Add a new
connection_accept_handlerparameter towebsocket_listener, which can be used to customize how a connection is accepted, for example to add headers or subprotocolsReferences: litestar-org/litestar#1571, litestar-org/litestar#1572
- Testing: Add 
blockandtimeoutparameters toWebSocketTestSessionreceive methods# Two parameters,
blockandtimeouthave been added to the following methods:References: litestar-org/litestar#1593
- CLI: Add 
--app-diroption to root command# The
--app-diroption was added to the root CLI command, allowing to set the run applications from a path that’s not the current working directory.References: litestar-org/litestar#1506
- WebSockets: Data iterators#
 Two new methods were added to the
WebSocketconnection, which allow to continuously receive data and iterate over it:References: litestar-org/litestar#1626
- WebSockets: MessagePack support#
 Add support for MessagePack to the
WebSocketconnection.Three new methods have been added for handling MessagePack:
In addition, two MessagePack related methods were added to
WebSocketTestSession:References: litestar-org/litestar#1626
- SQLAlchemy repository: Add support for sentinel column#
 This change adds support for
sentinel columnfeature added insqlalchemy2.0.10. Without it, there are certain cases whereadd_manyraises an exception.The
_sentinelvalue added to the declarative base should be excluded from normal select operations automatically and is excluded in theto_dictmethods.References: litestar-org/litestar#1603
- DTO: Alias generator for field names#
 A new argument
rename_strategyhas been added to theDTOConfig, allowing to remap field names with strategies such as “camelize”.References: litestar-org/litestar#1590
- DTO: Nested field exclusion#
 This feature adds support for excluding nested model fields using dot-notation, e.g.,
"a.b"excludes fieldbfrom nested model fieldaReferences: litestar-org/litestar#1197, litestar-org/litestar#1596
- WebSockets: Managing a socket’s lifespan using a context manager in websocket listeners#
 Changes the way a socket’s lifespan - accepting the connection and calling the appropriate event hooks - to use a context manager.
The
connection_lifespanargument was added to theWebSocketListener, which accepts an asynchronous context manager, which can be used to handle the lifespan of the socket.References: litestar-org/litestar#1625
- New module: Channels#
 A new module channels has been added: A general purpose event streaming library, which can for example be used to broadcast messages via WebSockets.
References: litestar-org/litestar#1587
Bugfixes#
- Relax typing of 
**kwargsinASGIConnection.url_for# Change the typing of the
**kwargsinASGIConnection.url_forfromdict[str, Any]toAnyReferences: litestar-org/litestar#1610
- Fix: Using 
websocket_listenerin controller causesTypeError# A bug was fixed that would cause a type error when using a
websocket_listenerin aControllerReferences: litestar-org/litestar#1615, litestar-org/litestar#1627
Other changes#
- DTO: Undocumented 
dto.factory.backendshas been made private#breaking The undocumented
dto.factory.backendsmodule has been made privateReferences: litestar-org/litestar#1589
2.0.0alpha5#
Features#
- Pass template context to HTMX template response#
 Pass the template context to the
Templatereturned byhtmx.Response.References: litestar-org/litestar#1488
- OpenAPI support for attrs and msgspec classes#
 Support OpenAPI schema generation for attrs classes and msgspec
Structs.References: litestar-org/litestar#1487
- SQLAlchemy repository: Add 
ModelProtocol# Add a new class
contrib.sqlalchemy.base.ModelProtocol, serving as a generic model base type, allowing to specify custom base classes while preserving typing informationReferences: litestar-org/litestar#1503
- SQLAlchemy repository: Support MySQL/MariaDB#
 Add support for MySQL/MariaDB to the SQLAlchemy repository, using the asyncmy driver.
References: litestar-org/litestar#1345
- SQLAlchemy repository: Support MySQL/MariaDB#
 Add support for MySQL/MariaDB to the SQLAlchemy repository, using the asyncmy driver.
References: litestar-org/litestar#1345
- SQLAlchemy repository: Add matching logic to 
get_or_create# Add a
match_fieldsargument tolitestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.get_or_create. This lets you lookup a model using a subset of the kwargs you’ve provided. If the remaining kwargs are different from the retrieved model’s stored values, an update is performed.References: litestar-org/litestar#1345
- Repository: Extend filter types#
 Add new filters
litestar.contrib.repository.filters.OrderByandlitestar.contrib.repository.filters.SearchFilter, providingORDER BY ...andLIKE .../ILIKE ...clauses respectivelyReferences: litestar-org/litestar#1345
- DTO: Add 
AbstractDTOFactoryand backends# An all-new DTO implementation was added, using
AbstractDTOFactoryas a base class, providing Pydantic and msgspec backends to facilitate (de)serialization and validation.References: litestar-org/litestar#1461
- WebSockets: Support DTOs in listeners#
 Support for DTOs has been added to
WebSocketListenerandWebSocketListener. Adtoandreturn_dtoparameter has been added, providing the same functionality as their route handler counterparts.References: litestar-org/litestar#1518
- DTO based serialization plugin#breaking
 SerializationPluginProtocolhas been re-implemented, leveraging the newDTOInterface.If a handler defines a plugin supported type as either the
datakwarg type annotation, or as the return annotation for a handler function, and no DTO has otherwise been resolved to handle the type, the protocol creates a DTO implementation to represent that type which is then used to de-serialize into, and serialize from instances of that supported type.Important
The Piccolo ORM and Tortoise ORM plugins have been removed by this change, but will be re-implemented using the new patterns in a future release leading up to the 2.0 release.
References: litestar-org/litestar#1501
Bugfixes#
- Fix inconsistent parsing of unix timestamp between Pydantic and cattrs#
 Timestamps parsed as
datewith Pydantic return a UTC date, while cattrs implementation return a date with the local timezone.This was corrected by forcing dates to UTC when being parsed by attrs.
References: litestar-org/litestar#1491, litestar-org/litestar#1492
- Fix: Retrieve type hints from class with no 
__init__method causes error# An error would occur when using a callable without an
object.__init__()method was used in a placed that would cause it to be inspected (such as a route handler’s signature).This was caused by trying to access the
__module__attribute ofobject.__init__(), which would fail with'wrapper_descriptor' object has no attribute '__module__'
References: litestar-org/litestar#1504, litestar-org/litestar#1505
- Fix error raised for partially installed attrs dependencies#
 An error was fixed that would cause a
MissingDependencyExceptionto be raised when dependencies for attrs were partially installed. This was fixed by being more specific about the missing dependencies in the error messages.References: litestar-org/litestar#1543
- Remove bool coercion in URL parsing#breaking
 When defining a query parameter as
param: str, and passing it a string value of"true", the value received by the route handler was the string"True", having been title cased. The same was true for the value of"false".This has been fixed by removing the coercing of boolean-like values during URL parsing and leaving it up to the parsing utilities of the receiving side (i.e. the handler’s signature model) to handle these values according to the associated type annotations.
References: litestar-org/litestar#1547, litestar-org/litestar#1550
- Fix missing 
content-encodingheaders on gzip/brotli compressed files# Fixed a bug that would cause static files served via
StaticFilesConfigthat have been compressed with gripz or brotli to miss the appropriatecontent-encodingheader.References: litestar-org/litestar#1576, litestar-org/litestar#1577
Other changes#
- SQLAlchemy repository: Rename 
SQLAlchemyRepository>SQLAlchemyAsyncRepository#breaking SQLAlchemyRepositoryhas been renamed tolitestar.contrib.sqlalchemy.repository.SQLAlchemyAsyncRepository.References: litestar-org/litestar#1345
- DTO: Remove 
from_connection/ extendfrom_data#breaking The method
DTOInterface.from_connectionhas been removed and replaced byDTOInterface.from_bytes, which receives both the raw bytes from the connection, and the connection instance. Sincefrom_bytesnow does not handle connections anymore, it can also be a synchronous method, improving symmetry withDTOInterface.from_bytes.The signature of
from_datahas been changed to also accept the connection, matchingfrom_bytes’ signature.As a result of these changes,
DTOInterface.from_bytesno longer needs to receive the connection instance, so therequestparameter has been dropped.References: litestar-org/litestar#1500
- SQLAlchemy 1 contrib module removed#breaking
 As a result of the changes introduced in #1501, SQLAlchemy 1 support has been dropped.
Note
If you rely on SQLAlchemy 1, you can stick to Starlite 1.51 for now. In the future, a SQLAlchemy 1 plugin may be released as a standalone package.
References: litestar-org/litestar#1501
- Change 
MissingDependencyExceptionto be a subclass ofImportError# MissingDependencyExceptionis now a subclass ofImportError, to make handling cases where both of them might be raised easier.References: litestar-org/litestar#1557
- Update 
standardandfullpackage extras# Add SQLAlchemy, uvicorn, attrs and structlog to the
fullextraAdd uvicorn to the
standardextraAdd
uvicorn[standard]as an optional dependency to be used in the extras
References: litestar-org/litestar#1494
- Remove support for declaring DTOs as handler types#breaking
 Prior to this, a DTO type could be declared implicitly using type annotations. With the addition of the
dtoandreturn_dtoparameters, this feature has become superfluous and, in the spirit of offering only one clear way of doing things, has been removed.References: litestar-org/litestar#1534
- DTO: Simplify 
DTOConfig#breaking The
includeparameter has been removed, to provide a more accessible interface and avoid overly complex interplay withexcludeand its support for dotted attributesfield_mappinghas been renamed torename_fieldsand support to remap field types has been droppedexperimental
field_definitionshas been removed. It may be replaced with a “ComputedField” in a future release that will allow multiple field definitions to be added to the model, and a callable that transforms them into a value for a model field. See
References: litestar-org/litestar#1580
2.0.0alpha4#
Features#
attrsandmsgspecsupport inPartial#Partialnow supports constructing partial models for attrs and msgspecReferences: litestar-org/litestar#1462
Annotatedsupport for route handler and dependency annotations#Annotatedcan now be used in route handler and dependencies to specify additional information about the fields.@get("/") def index(param: int = Parameter(gt=5)) -> dict[str, int]: ...
@get("/") def index(param: Annotated[int, Parameter(gt=5)]) -> dict[str, int]: ...
References: litestar-org/litestar#1462
Bugfixes#
- Support 
text/htmlMedia-Type inRedirectresponse container# The media type in
Redirectwon’t be forced totext/plainanymore and now supports setting arbitrary media types.References: litestar-org/litestar#1451, litestar-org/litestar#1474
- Fix global namespace for type resolution#
 Fix a bug where certain annotations would cause a
NameErrorReferences: litestar-org/litestar#1472, litestar-org/litestar#1477
- Add uvicorn to 
cliextra# Add the
uvicornpackage to thecliextra, as it is required unconditionallyReferences: litestar-org/litestar#1478, litestar-org/litestar#1480
- Update logging levels when setting 
Litestar.debugdynamically# When passing
debug=TruetoLitestar, thelitestarlogger would be set up in debug mode, but changing thedebugattribute after the class had been instantiated did not update the logger accordingly.This lead to a regression where the
--debugflag to the CLI’sruncommand would no longer have the desired affect, as loggers would still be on theINFOlevel.References: litestar-org/litestar#1476, litestar-org/litestar#1482
2.0.0alpha3#
Features#
- SQLAlchemy 2.0 Plugin#
 A
SQLAlchemyInitPluginwas added, providing support for managed synchronous and asynchronous sessions.See also
References: litestar-org/litestar#1395
- Attrs signature modelling#
 Added support to model route handler signatures with attrs instead of Pydantic
References: litestar-org/litestar#1382
- Support setting status codes in 
Redirectcontainer# Add support for manually setting status codes in the
RedirectResponseresponse container. This was previously only possible by setting thestatus_codeparameter on the corresponding route handler, making dynamic redirect status codes and conditional redirects using this container hard to implement.References: litestar-org/litestar#1371, litestar-org/litestar#1412
- Sentinel value to support caching responses indefinitely#
 Add the
CACHE_FOREVERsentinel value, that, when passed to a route handlerscache argument, will cause it to be cached forever, skipping the default expiration.Additionally, add support for setting
ResponseCacheConfig.default_expirationtoNone, allowing to cache values indefinitely by default when settingcache=Trueon a route handler.References: litestar-org/litestar#1365, litestar-org/litestar#1414
- Accept-header parsing and content negotiation#
 Add an
acceptproperty toRequest, returning the newly addedAcceptheader wrapper, representing the requestsAcceptHTTP header, offering basic content negotiation.See also
References: litestar-org/litestar#1317
- Enhanced WebSockets support#
 Add a new set of features for handling WebSockets, including automatic connection handling, (de)serialization of incoming and outgoing data analogous to route handlers and OOP based event dispatching.
See also
References: litestar-org/litestar#1402
Bugfixes#
- SQLAlchemy 1 plugin mutates app state destructively#
 When using the SQLAlchemy 1 plugin, repeatedly running through the application lifecycle (as done when testing an application not provided by a factory function), would result in a
KeyErroron the second pass.This was caused be the plugin’s
on_shutdownhandler deleting theengine_app_state_keyfrom the application’s state on application shutdown, but only adding it on application init.This was fixed by adding performing the necessary setup actions on application startup rather than init.
References: litestar-org/litestar#1368, litestar-org/litestar#1391
- Fix SQLAlchemy 1 Plugin - 
'Request' object has no attribute 'dict'# An annotation such as
async def provide_user(request: Request[User, Token, Any]) -> User: ...
would result in the error
'Request' object has no attribute 'dict'.This was fixed by changing how
get_plugin_for_valueinteracts withtyping.get_args()References: litestar-org/litestar#1388, litestar-org/litestar#1389
- Support OpenAPI schema generation with stringized return annotation#
 The following code would result in non-specific and incorrect information being generated for the OpenAPI schema:
from __future__ import annotations from starlite import get @get("/") def hello_world() -> dict[str, str]: return {"hello": "world"}
This could be alleviated by removing
from __future__ import annotations. Stringized annotations in any form are now fully supported.References: litestar-org/litestar#1409, litestar-org/litestar#1410
- Fix OpenAPI schema generation crashes for models with 
Annotatedtype attribute# When using a model that includes a type annotation with
typing.Annotatedin a route handler, the interactive documentation would raise an error when accessed. This has been fixed andtyping.Annotatedis now fully supported.References: litestar-org/litestar#1372, litestar-org/litestar#1400
- Support empty 
datainRequestFactory# Add support for passing an empty
dataparameter to aRequestFactory, which would previously lead to an error.References: litestar-org/litestar#1419, litestar-org/litestar#1420
Other changes#
create_test_clientandcrate_async_test_clientsignatures and docstrings to to matchLitestar#Add missing parameters to
create_test_clientandcreate_test_client. The following parameters were added:cache_controldebugetagoptresponse_cache_configresponse_cookiesresponse_headerssecuritystorestagstype_encoders
References: litestar-org/litestar#1417
2.0.0alpha2#
Features#
- Repository contrib & SQLAlchemy repository#
 Add a a
repositorymodule tocontrib, providing abstract base classes to implement the repository pattern. Also added was thecontrib.repository.sqlalchemymodule, implementing a SQLAlchemy repository, offering hand-tuned abstractions over commonly used tasks, such as handling of object sessions, inserting, updating and upserting individual models or collections.References: litestar-org/litestar#1254
- Data stores & registry#breaking
 The
starlite.storagemodule added in the previous version has been renamedstarlite.storesto reduce ambiguity, and a new feature, thestarlite.stores.registry.StoreRegistryhas been introduced; It serves as a central place to manage stores and reduces the amount of configuration needed for various integrations.Add
storeskwarg toStarliteandAppConfigto allow seeding of theStoreRegistryAdd
Starlite.storesattribute, containing aStoreRegistryChange
RateLimitMiddlewareto useapp.storesChange request caching to use
app.storesChange server side sessions to use
app.storesMove
starlite.config.cache.CacheConfigtostarlite.config.response_cache.ResponseCacheConfigRename
Starlite.cache_config>Starlite.response_cache_configRename
AppConfig.cache_config>response_cache_configRemove
starlite/cachemoduleRemove
ASGIConnection.cachepropertyRemove
Starlite.cacheattribute
Attention
starlite.middleware.rate_limit.RateLimitMiddleware,starlite.config.response_cache.ResponseCacheConfig, andstarlite.middleware.session.server_side.ServerSideSessionConfiginstead of accepting astorageargument that could be passed aStorageinstance now have to be configured via thestoreattribute, accepting a string key for the store to be used from the registry. Thestoreattribute has a unique default set, guaranteeing a uniquestarlite.stores.memory.MemoryStoreinstance is acquired for every one of them from the registry by defaultSee also
References: litestar-org/litestar#1330
- Add 
starlite.__version__# Add a
__version__constant to thestarlitenamespace, containing aNamedTuple, holding information about the currently installed version of StarliteReferences: litestar-org/litestar#1277
- Add 
starlite versioncommand to CLI# Add a new
versioncommand to the CLI which displays the currently installed version of StarliteReferences: litestar-org/litestar#1322
- Enhance CLI autodiscovery logic#breaking
 Update the CLI Autodiscovery to only consider canonical modules app and application, but every
starlite.app.Starliteinstance or application factory able to return aStarliteinstance within those or one of their submodules, giving priority to the canonical names app and application for application objects and submodules containing them.See also
References: litestar-org/litestar#1322
- Configurable exception logging and traceback truncation#
 Add three new configuration options to
starlite.logging.config.BaseLoggingConfig:starlite.logging.config.LoggingConfig.log_exceptionsConfigure when exceptions are logged.
alwaysAlways log exceptions
debugLog exceptions in debug mode only
neverNever log exception
starlite.logging.config.LoggingConfig.traceback_line_limitConfigure how many lines of tracback are logged
starlite.logging.config.LoggingConfig.exception_logging_handlerA callable that receives three parameters - the
app.logger, the connection scope and the traceback list, and should handle logging
See also
starlite.logging.config.LoggingConfigReferences: litestar-org/litestar#1296
Bugfixes#
- Allow overwriting default OpenAPI response descriptions#
 Fix litestar-org/litestar#1292 by allowing to overwrite the default OpenAPI response description instead of raising
ImproperlyConfiguredException.References: litestar-org/litestar#1292, litestar-org/litestar#1293
- Fix regression in path resolution that prevented 404’s being raised for false paths#breaking
 Invalid paths within controllers would under specific circumstances not raise a 404. This was a regression compared to
v1.51Note
This has been marked as breaking since one user has reported to rely on this “feature”
References: litestar-org/litestar#1316
- Fix 
after_requesthook not being called on responses returned from handlers# after_requesthooks were not being called automatically when astarlite.response.Responseinstances was returned from a route handler directly.See also
References: litestar-org/litestar#1315, litestar-org/litestar#1344
- Fix 
SQLAlchemyPluginraises error when using SQLAlchemy UUID# An error would be raised when using the SQLAlchemy plugin with a sqlalchemy UUID. This was fixed by adding it to the provider map.
References: litestar-org/litestar#1355
- Fix 
JSON.parseerror in ReDoc and Swagger OpenAPI handlers# The HTML generated by the ReDoc and Swagger OpenAPI handlers would cause JSON.parse to throw an error. This was fixed by removing the call to
JSON.parse.References: litestar-org/litestar#1363
- Fix CLI prints application info twice#
 Fix an error where the CLI would print application info twice on startup
References: litestar-org/litestar#1322
Other changes#
- Update 
SimpleEventEmitterto use worker pattern# starlite.events.emitter.SimpleEventEmitterwas updated to using an async worker, pulling emitted events from a queue and subsequently calling listeners. Previously listeners were called immediately, making the operation effectively “blocking”.References: litestar-org/litestar#1346
- Make 
BaseEventEmitterBackend.emitsynchronous#breaking starlite.events.emitter.BaseEventEmitterBackend, and subsequentlystarlite.events.emitter.SimpleEventEmitterandstarlite.app.Starlite.emithave been changed to synchronous function, allowing them to easily be used within synchronous route handlers.References: litestar-org/litestar#1376
- Move 3rd party integration plugins to 
contrib#breaking Move
plugins.piccolo_orm>contrib.piccolo_ormMove
plugins.tortoise_orm>contrib.tortoise_orm
References: litestar-org/litestar#1279, litestar-org/litestar#1252
- Remove 
picologgingdependency from thestandardpackage extra#breaking picologging has been removed form the
standardpackage extra. If you have been previously relying on this, you need to changepip install starlite[standard]topip install starlite[standard,picologging]References: litestar-org/litestar#1313
- Replace 
Starlite()initial_statekeyword argument withstate#breaking The
initial_stateargument tostarlite.app.Starlitehas been replaced with astatekeyword argument, accepting an optionalstarlite.datastructures.state.Stateinstance.Existing code using this keyword argument will need to be changed from
from starlite import Starlite app = Starlite(..., initial_state={"some": "key"})
to
from starlite import Starlite from starlite.datastructures.state import State app = Starlite(..., state=State({"some": "key"}))
References: litestar-org/litestar#1350
- Remove support for 2 argument form of 
before_send#breaking before_sendhook handlers initially accepted 2 arguments, but support for a 3 argument form was added later on, accepting an additionalscopeparameter. Support for the 2 argument form has been dropped with this release.See also
References: litestar-org/litestar#1354
- Standardize module exports#breaking
 A large refactoring standardising the way submodules make their names available.
The following public modules have changed their location:
config.openapi>openapi.configconfig.logging>logging.configconfig.template>template.configconfig.static_files>static_files.config
The following modules have been removed from the public namespace:
asgikwargsmiddleware.utilscli.utilscontrib.htmx.utilshandlers.utilsopenapi.constantsopenapi.enumsopenapi.datastructuresopenapi.parametersopenapi.path_itemopenapi.request_bodyopenapi.responsesopenapi.schemaopenapi.typescript_converteropenapi.utilsmultipartparserssignature
References: litestar-org/litestar#1273
2.0.0alpha1#
Features#
- Validation of controller route handler methods#
 Starlite will now validate that no duplicate handlers (that is, they have the same path and same method) exist.
References: litestar-org/litestar#1144
- HTMX support#
 Basic support for HTMX requests and responses.
References: litestar-org/litestar#1086
- Alternate constructor 
Starlite.from_config# starlite.app.Starlite.from_configwas added to thestarlite.app.Starliteclass which allows to construct an instance from anstarlite.config.app.AppConfiginstance.References: litestar-org/litestar#1190
- Web concurrency option for CLI 
runcommand# A
--wc/ –web-concurrency` option was added to thestarlite runcommand, enabling users to specify the amount of worker processes to use. A corresponding environment variableWEB_CONCURRENCYwas added as wellReferences: litestar-org/litestar#1218
- Validation of 
stateparameter in handler functions# Type annotations of the reserved
stateparameter in handler functions will now be validated such that annotations using an unsupported type will raise astarlite.exceptions.ImproperlyConfiguredException.References: litestar-org/litestar#1264
- Generic application state#
 starlite.connection.base.ASGIConnectionand its subclasses are now generic onStatewhich allow to to fully type hint a request asRequest[UserType, AuthType, StateType].References: litestar-org/litestar#1030
- Dependency injection of classes#
 Support using classes (not class instances, which were already supported) as dependency providers. With this, now every callable is supported as a dependency provider.
References: litestar-org/litestar#1143
- Event bus#
 A simple event bus system for Starlite, supporting synchronous and asynchronous listeners and emitters, providing a similar interface to handlers. It currently features a simple in-memory, process-local backend
References: litestar-org/litestar#1105
- Unified storage interfaces#breaking
 Storage backends for server-side sessions
starlite.cache.Cache`have been unified and replaced by thestarlite.storages, which implements generic asynchronous key/values stores backed by memory, the file system or redis.Important
This is a breaking change and you need to change your session / cache configuration accordingly
References: litestar-org/litestar#1184
Bugfixes#
- Fix resolving of relative paths in 
StaticFilesConfig# Using a relative
pathlib.Pathdid not resolve correctly and result in aNotFoundExceptionReferences: litestar-org/litestar#1256
- Fix 
--reloadflag tostarlite runnot working correctly# Passing the
--reloadflag to thestarlite runcommand did not work correctly in all circumstances due to an issue with uvicorn. This was resolved by invoking uvicorn in a subprocess.References: litestar-org/litestar#1191
- Fix optional types generate incorrect OpenAPI schemas#
 An optional query parameter was incorrectly represented as
{ "oneOf": [ { "type": null" }, { "oneOf": [] } ]}
References: litestar-org/litestar#1210
- Fix 
LoggingMiddlewareis sending obfuscated session id to client# LoggingMiddlewarewould in some cases send obfuscated data to the client, due to a bug in the obfuscation function which obfuscated values in the input dictionary in-place.References: litestar-org/litestar#1228
- Fix missing 
domainconfiguration value for JWT cookie auth# starlite.contrib.jwt.jwt_auth.JWTCookieAuthdidn’t set thedomainconfiguration value on the response cookie.References: litestar-org/litestar#1223
- Fix litestar-org/litestar#1201: Can not serve static file in 
/path# A validation error made it impossible to serve static files from the root path
/.References: litestar-org/litestar#1201
- Fix litestar-org/litestar#1149: Middleware not excluding static path#
 A middleware’s
excludeparameter would sometimes not be honoured if the path was used to serve static files usingStaticFilesConfigReferences: litestar-org/litestar#1149
Other changes#
- Relaxed type annotations#
 Type annotations across the library have been relaxed to more generic forms, for example
Iterable[str]instead ofList[str]orMapping[str, str]instead ofDict[str, str].References: litestar-org/litestar#1140
type_encoderssupport inAbstractSecurityConfig#type_encoderssupport has been added tostarlite.security.base.AbstractSecurityConfig, enabling support for customizedtype_encodersfor example instarlite.contrib.jwt.jwt_auth.JWTAuth.References: litestar-org/litestar#1167
- Renamed handler module names#breaking
 The modules containing route handlers have been renamed to prevent ambiguity between module and handler names.
starlite.handlers.asgi>starlite.handlers.asgi_handlersstarlite.handlers.http>starlite.handlers.http_handlersstarlite.handlers.websocket>starlite.handlers.websocket_handlers
References: litestar-org/litestar#1170
- New plugin protocols#breaking
 The plugin protocol has been split into three distinct protocols, covering different use cases:
starlite.plugins.InitPluginProtocolHook into an application’s initialization process
starlite.plugins.SerializationPluginProtocolExtend the serialization and deserialization capabilities of an application
starlite.plugins.OpenAPISchemaPluginProtocolExtend OpenAPI schema generation
References: litestar-org/litestar#1176
- Unify response headers and cookies#breaking
 response headers and response cookies now have the same interface, along with the
headersandcookieskeyword arguments tostarlite.response.Response. They each allow to pass either a :class:`Mapping[str, str] <typing.Mapping>, e.g. a dictionary, or aSequenceofstarlite.datastructures.response_header.ResponseHeaderorstarlite.datastructures.cookie.Cookierespectively.References: litestar-org/litestar#1209
- Replace Pydantic models with dataclasses#breaking
 Several Pydantic models used for configuration have been replaced with dataclasses or plain classes. This change should be mostly non-breaking, unless you relied on those configuration objects being Pydantic models. The changed models are:
starlite.config.allowed_hosts.AllowedHostsConfigstarlite.config.app.AppConfigstarlite.config.response_cache.ResponseCacheConfigstarlite.config.compression.CompressionConfigstarlite.config.cors.CORSConfigstarlite.config.csrf.CSRFConfigstarlite.logging.config.LoggingConfigstarlite.openapi.OpenAPIConfigstarlite.static_files.StaticFilesConfigstarlite.template.TemplateConfigstarlite.contrib.jwt.jwt_token.Tokenstarlite.contrib.jwt.jwt_auth.JWTAuthstarlite.contrib.jwt.jwt_auth.JWTCookieAuthstarlite.contrib.jwt.jwt_auth.OAuth2Loginstarlite.contrib.jwt.jwt_auth.OAuth2PasswordBearerAuthstarlite.contrib.opentelemetry.OpenTelemetryConfigstarlite.middleware.logging.LoggingMiddlewareConfigstarlite.middleware.rate_limit.RateLimitConfigstarlite.middleware.session.base.BaseBackendConfigstarlite.middleware.session.client_side.CookieBackendConfigstarlite.middleware.session.server_side.ServerSideSessionConfigstarlite.response_containers.ResponseContainerstarlite.response_containers.Filestarlite.response_containers.Redirectstarlite.response_containers.Streamstarlite.security.base.AbstractSecurityConfigstarlite.security.session_auth.SessionAuth
References: litestar-org/litestar#1242
- SQLAlchemy plugin moved to 
contrib#breaking The
SQLAlchemyPlugin` has moved to ``starlite.contrib.sqlalchemy_1.pluginand will only be compatible with the SQLAlchemy 1.4 release line. The newer SQLAlchemy 2.x releases will be supported by thecontrib.sqlalchemymodule.References: litestar-org/litestar#1252
- Cleanup of the 
starlitenamespace#breaking The
starlitenamespace has been cleared up, removing many names from it, which now have to be imported from their respective submodules individually. This was both done to improve developer experience as well as reduce the time it takes toimport starlite.References: litestar-org/litestar#1135