Package: litestar
ProjectStatusCI/CDQualityPackageCommunityMetaLitestar is a powerful, flexible yet opinionated ASGI framework, focused on
building APIs, and offers high-performance data validation and parsing,
dependency injection, first-class ORM integration, authorization primitives, and much
more that's needed to get applications up and running.Check out thedocumentation 📚for a detailed overview of
its features!Additionally, theLitestar fullstack repositorycan give you a good impression how a fully fledged Litestar application may look.Table of ContentsInstallationQuick StartCore FeaturesExample ApplicationsFeaturesClass-based ControllersData Parsing, Type Hints, and MsgspecPlugin System, ORM support, and DTOsOpenAPIDependency InjectionMiddlewareRoute GuardsRequest Life Cycle HooksPerformanceContributingInstallationpipinstalllitestarQuick StartfromlitestarimportLitestar,get@get("/")defhello_world()->dict[str,str]:"""Keeping the tradition alive with hello world."""return{"hello":"world"}app=Litestar(route_handlers=[hello_world])Core FeaturesClass based controllersDependency InjectionLayered MiddlewarePlugin SystemOpenAPI 3.1 schema generationLife Cycle HooksRoute Guards based AuthorizationSupport fordataclasses,TypedDict,pydantic version 1 and version 2,msgspecandattrsLayered parameter declarationAutomatic API documentation with:RapiDocRedocStoplight ElementsSwagger-UITriosupport (built-in, viaAnyIO)Ultra-fast validation, serialization and deserialization usingmsgspecSQLAlchemy integrationPiccolo ORM SupportExample ApplicationsPre-built Example Appslitestar-pg-redis-docker: In addition to Litestar, this
demonstrates a pattern of application modularity, SQLAlchemy 2.0 ORM, Redis cache connectivity, and more. Like all
Litestar projects, this application is open to contributions, big and small.litestar-fullstack: A reference application that contains most of the boilerplate required for a web application.
It features a Litestar app configured with best practices, SQLAlchemy 2.0 and SAQ, a frontend integrated with Vitejs and Jinja2 templates, Docker, and more.litestar-hello-world: A bare-minimum application setup. Great
for testing and POC work.SponsorsLitestar is an open-source project, and we enjoy the support of our sponsors to help fund the exciting
work we do.Ahugethanks to our sponsors:Check out our sponsors in the docsIf you would like to support the work that we do please considerbecoming a sponsoronGitHuborOpen Collective.We also participate in pledge-based sponsorship withPolar.FeaturesClass-based ControllersWhile supporting function-based route handlers, Litestar also supports and promotes python OOP using class based
controllers:Example for class-based controllersfromtypingimportList,OptionalfromdatetimeimportdatetimefromlitestarimportController,get,post,put,patch,deletefromlitestar.dtoimportDTODatafrompydanticimportUUID4frommy_app.modelsimportUser,PartialUserDTOclassUserController(Controller):path="/users"@post()asyncdefcreate_user(self,data:User)->User:...@get()asyncdeflist_users(self)->List[User]:...@get(path="/{date:int}")asyncdeflist_new_users(self,date:datetime)->List[User]:...@patch(path="/{user_id:uuid}",dto=PartialUserDTO)asyncdefpartial_update_user(self,user_id:UUID4,data:DTOData[PartialUserDTO])->User:...@put(path="/{user_id:uuid}")asyncdefupdate_user(self,user_id:UUID4,data:User)->User:...@get(path="/{user_name:str}")asyncdefget_user_by_name(self,user_name:str)->Optional[User]:...@get(path="/{user_id:uuid}")asyncdefget_user(self,user_id:UUID4)->User:...@delete(path="/{user_id:uuid}")asyncdefdelete_user(self,user_id:UUID4)->None:...Data Parsing, Type Hints, and MsgspecLitestar is rigorously typed, and it enforces typing. For example, if you forget to type a return value for a route
handler, an exception will be raised. The reason for this is that Litestar uses typing data to generate OpenAPI specs,
as well as to validate and parse data. Thus, typing is essential to the framework.Furthermore, Litestar allows extending its support using plugins.Plugin System, ORM support, and DTOsLitestar has a plugin system that allows the user to extend serialization/deserialization, OpenAPI generation, and other
features.It ships with a builtin plugin for SQL Alchemy, which allows the user to use SQLAlchemy declarative classes "natively"
i.e., as type parameters that will be serialized/deserialized and to return them as values from route
handlers.Litestar also supports the programmatic creation of DTOs with aDTOFactoryclass, which also supports the use of
plugins.OpenAPILitestar has custom logic to generate OpenAPI 3.1.0 schema, include optional generation of examples using thepolyfactorylibrary.ReDoc, Swagger-UI and Stoplight Elements API DocumentationLitestar serves the documentation from the generated OpenAPI schema with:ReDocSwagger-UIStoplight ElementsRapiDocAll these are available and enabled by default.Dependency InjectionLitestar has a simple but powerful DI system inspired by pytest. You can define named dependencies - sync or async - at
different levels of the application, and then selective use or overwrite them.Example for DIfromlitestarimportLitestar,getfromlitestar.diimportProvideasyncdefmy_dependency()->str:...@get("/")asyncdefindex(injected:str)->str:returninjectedapp=Litestar([index],dependencies={"injected":Provide(my_dependency)})MiddlewareLitestar supports typical ASGI middleware and ships with middlewares to handle things such asCORSCSRFRate limitingGZip and Brotli compressionClient- and server-side sessionsRoute GuardsLitestar has an authorization mechanism calledguards, which allows the user to define guard functions at different
level of the application (app, router, controller etc.) and validate the request before hitting the route handler
function.Example for route guardsfromlitestarimportLitestar,getfromlitestar.connectionimportASGIConnectionfromlitestar.handlers.baseimportBaseRouteHandlerfromlitestar.exceptionsimportNotAuthorizedExceptionasyncdefis_authorized(connection:ASGIConnection,handler:BaseRouteHandler)->None:# validate authorization# if not authorized, raise NotAuthorizedExceptionraiseNotAuthorizedException()@get("/",guards=[is_authorized])asyncdefindex()->None:...app=Litestar([index])Request Life Cycle HooksLitestar supports request life cycle hooks, similarly to Flask - i.e.before_requestandafter_requestPerformanceLitestar is fast. It is on par with, or significantly faster than comparable ASGI frameworks.You can see and run the benchmarkshere,
or read more about itherein our documentation.ContributingLitestar is open to contributions big and small. You can alwaysjoin our discordserver
orjoin our Matrixspace
to discuss contributions and project maintenance. For guidelines on how to contribute, please
seethe contribution guide.Contributors ✨Thanks goes to these wonderful people:Emoji KeyNa'aman Hirschfeld🚧💻📖⚠️🤔💡🐛Peter Schutt🚧💻📖⚠️🤔💡🐛Ashwin Vinod💻📖Damian📖Vincent Sarago💻Jonas Krüger Svensson📦Sondre Lillebø Gundersen📦Lev💻🤔Tim Wedde💻Tory Clasen💻Arseny Boykov💻🤔Jacob Rodgers💡Dane Solberg💻madlad33💻Matthew Aylward💻Jan Klima💻C2D⚠️to-ph💻imbev📖cătălin💻Seon82📖Slava💻Harry💻📖Cody Fincher🚧💻📖⚠️🤔💡🐛Christian Clauss📖josepdaniel💻devtud🐛Nicholas Ramos💻seladb📖💻Simon Wienhöfer💻MobiusXS💻Aidan Simard📖wweber💻Samuel Colvin💻Mateusz Mikołajczyk💻Alex💻Odiseo📖Javier  Pinilla💻Chaoying📖infohash💻John Ingles💻Eugene⚠️💻Jon Daly📖💻Harshal Laheri💻📖Téva KRIEF💻Konstantin Mikhailov🚧💻📖⚠️🤔💡🐛Mitchell Henry📖chbndrhnns📖nielsvanhooy💻🐛⚠️provinzkraut🚧💻📖⚠️🤔💡🐛🎨Joshua Bronson📖Roman Reznikov📖mookrs📖Mike DePalatis📖Carlos Alberto Pérez-Molano📖ThinksFast⚠️📖Christopher Krause💻Kyle Smith💻📖🐛Scott Bradley🐛Srikanth Chekuri⚠️📖Michael Bosch📖sssssss340🐛ste-pool💻🚇Alc-Alc📖💻⚠️asomethings💻Garry Bullock📖Niclas Haderer💻Diego Alvarez📖💻⚠️Jason Nance📖Igor Kapadze📖Somraj Saha📖Magnús Ágúst Skúlason💻📖Alessio Parma📖Peter Brunner💻Jacob Coffee📖💻⚠️🚇🤔🚧💼🎨Gamazic💻Kareem Mahlees💻Abdulhaq Emhemmed💻📖Jenish💻📖chris-telemetry💻Ward🐛Stephan Fitzpatrick🐛Eric Kennedy📖wassaf shahzad💻Nils Olsson💻🐛Riley Chase💻arl🚧Antoine van der Horst📖Nick Groenen📖Giorgio Vilardo📖Nicholas Bollweg💻Tomas Jonsson⚠️💻Khiem Doan📖kedod📖sonpro1296💻⚠️🚇📖Patrick Armengol📖Sander📖疯人院主任📖aviral-nayya💻whiskeyriver💻Phyo Arkar Lwin💻MatthewNewland🐛💻⚠️Tom Kuo🐛LeckerenSirupwaffeln🐛Daniel González Fernández📖01EK98📖Sarbo Roy💻Ryan Seeley💻Felix📖🐛George Sakkis💻Huba Tuba📖Stefane Fermigier📖r4ge💻📖Jay💻sinisaos📖Tharuka Devendra💻euri10💻📖🐛Shubham📖Erik Hasse🐛💻Nikita Sobolev🚇💻Nguyễn Hoàng Đức🐛RavanaBhrama📖Marcel Johannesmann📖Matthew📖Mattwmaster58🐛💻⚠️Manuel Sanchez Pinar📖Juan Riveros📖David Brochart📖Sean Donoghue📖P.C. Shyamshankar🐛💻⚠️William Evonosky💻geeshta📖💻🐛Robert Rosca📖DICE_Lab💻Luis San Pablo💻⚠️📖Pastukhov Nikita📖James O'Claire📖Pete📖Alexandre Richonnier💻📖betaboon💻Dennis Brakhane💻🐛Pragy Agarwal📖Piotr Dybowski📖Konrad Szczurek📖⚠️Orell Garten💻📖⚠️Julien📖Leejay Hsu🚧🚇📖Michiel W. Beijen📖L. Bao📖Jarred Glaser📖Hunter Boyd📖Cesar Giulietti📖Marcus Lim📖Henry Zhou🐛💻William Stam📖andrew do💻⚠️📖Boseong Choi💻⚠️Kim Minki💻📖Jeongseop Lim📖FergusMok📖💻⚠️Manu Singhal📖Jerry Wu📖horo🐛Ross Titmarsh💻Mike Korneev📖Patrick Neise💻Jean Arhancet🐛Leo Alekseyev💻This project follows theall-contributorsspecification.
Contributions of any kind welcome!