litestar2.12.1
Published
Litestar - A production-ready, highly performant, extensible ASGI API Framework
pip install litestar
Package Downloads
Project URLs
Requires Python
<4.0,>=3.8
Dependencies
- anyio
>=3
- click
- exceptiongroup
; python_version < "3.11"
- httpx
>=0.22
- importlib-metadata
; python_version < "3.10"
- importlib-resources
>=5.12.0; python_version < "3.9"
- msgspec
>=0.18.2
- multidict
>=6.0.2
- polyfactory
>=2.6.3
- pyyaml
- rich-click
- rich
>=13.0.0
- typing-extensions
- annotated-types
; extra == "annotated-types"
- attrs
; extra == "attrs"
- brotli
; extra == "brotli"
- jsbeautifier
; extra == "cli"
- uvicorn
[standard]; extra == "cli"
- uvloop
>=0.18.0; sys_platform != "win32" and extra == "cli"
- cryptography
; extra == "cryptography"
- advanced-alchemy
>=0.2.2; extra == "full"
- annotated-types
; extra == "full"
- attrs
; extra == "full"
- brotli
; extra == "full"
- cryptography
; extra == "full"
- email-validator
; extra == "full"
- fast-query-parsers
>=1.0.2; extra == "full"
- jinja2
; extra == "full"
- jinja2
>=3.1.2; extra == "full"
- jsbeautifier
; extra == "full"
- mako
>=1.2.4; extra == "full"
- minijinja
>=1.0.0; extra == "full"
- opentelemetry-instrumentation-asgi
; extra == "full"
- piccolo
; extra == "full"
- picologging
; extra == "full"
- prometheus-client
; extra == "full"
- pydantic
; extra == "full"
- pydantic-extra-types
; extra == "full"
- pyjwt
>=2.9.0; extra == "full"
- redis
[hiredis]>=4.4.4; extra == "full"
- structlog
; extra == "full"
- uvicorn
[standard]; extra == "full"
- uvloop
>=0.18.0; sys_platform != "win32" and extra == "full"
- jinja2
>=3.1.2; extra == "jinja"
- cryptography
; extra == "jwt"
- pyjwt
>=2.9.0; extra == "jwt"
- mako
>=1.2.4; extra == "mako"
- minijinja
>=1.0.0; extra == "minijinja"
- opentelemetry-instrumentation-asgi
; extra == "opentelemetry"
- piccolo
; extra == "piccolo"
- picologging
; extra == "picologging"
- prometheus-client
; extra == "prometheus"
- email-validator
; extra == "pydantic"
- pydantic
; extra == "pydantic"
- pydantic-extra-types
; extra == "pydantic"
- redis
[hiredis]>=4.4.4; extra == "redis"
- advanced-alchemy
>=0.2.2; extra == "sqlalchemy"
- fast-query-parsers
>=1.0.2; extra == "standard"
- jinja2
; extra == "standard"
- jsbeautifier
; extra == "standard"
- uvicorn
[standard]; extra == "standard"
- uvloop
>=0.18.0; sys_platform != "win32" and extra == "standard"
- structlog
; extra == "structlog"
Litestar 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 the documentation ๐ for a detailed overview of its features!
Additionally, the Litestar fullstack repository can give you a good impression how a fully fledged Litestar application may look.
Table of Contents
Installation
pip install litestar
Quick Start
from litestar import Litestar, get
@get("/")
def hello_world() -> dict[str, str]:
"""Keeping the tradition alive with hello world."""
return {"hello": "world"}
app = Litestar(route_handlers=[hello_world])
Core Features
- Class based controllers
- Dependency Injection
- Layered Middleware
- Plugin System
- OpenAPI 3.1 schema generation
- Life Cycle Hooks
- Route Guards based Authorization
- Support for
dataclasses
,TypedDict
, pydantic version 1 and version 2, msgspec and attrs - Layered parameter declaration
- Support for RFC 9457 standardized "Problem Detail" error responses
- Automatic API documentation with:
- Trio support (built-in, via AnyIO)
- Ultra-fast validation, serialization and deserialization using msgspec
- SQLAlchemy integration
- Piccolo ORM Support
Example Applications
Pre-built Example Apps
- litestar-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.
Sponsors
Litestar is an open-source project, and we enjoy the support of our sponsors to help fund the exciting work we do.
A huge thanks to our sponsors:
Check out our sponsors in the docs
If you would like to support the work that we do please consider becoming a sponsor via Polar.sh (preferred), GitHub or Open Collective.
Also, exclusively with Polar, you can engage in pledge-based sponsorships.
Features
Class-based Controllers
While supporting function-based route handlers, Litestar also supports and promotes python OOP using class based controllers:
Example for class-based controllers
from typing import List, Optional
from datetime import datetime
from litestar import Controller, get, post, put, patch, delete
from litestar.dto import DTOData
from pydantic import UUID4
from my_app.models import User, PartialUserDTO
class UserController(Controller):
path = "/users"
@post()
async def create_user(self, data: User) -> User: ...
@get()
async def list_users(self) -> List[User]: ...
@get(path="/{date:int}")
async def list_new_users(self, date: datetime) -> List[User]: ...
@patch(path="/{user_id:uuid}", dto=PartialUserDTO)
async def partial_update_user(
self, user_id: UUID4, data: DTOData[PartialUserDTO]
) -> User: ...
@put(path="/{user_id:uuid}")
async def update_user(self, user_id: UUID4, data: User) -> User: ...
@get(path="/{user_name:str}")
async def get_user_by_name(self, user_name: str) -> Optional[User]: ...
@get(path="/{user_id:uuid}")
async def get_user(self, user_id: UUID4) -> User: ...
@delete(path="/{user_id:uuid}")
async def delete_user(self, user_id: UUID4) -> None: ...
Data Parsing, Type Hints, and Msgspec
Litestar 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 DTOs
Litestar 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 a DTOFactory
class, which also supports the use of
plugins.
OpenAPI
Litestar has custom logic to generate OpenAPI 3.1.0 schema, include optional generation of examples using the
polyfactory
library.
ReDoc, Swagger-UI and Stoplight Elements API Documentation
Litestar serves the documentation from the generated OpenAPI schema with:
All these are available and enabled by default.
Dependency Injection
Litestar 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 DI
from litestar import Litestar, get
from litestar.di import Provide
async def my_dependency() -> str: ...
@get("/")
async def index(injected: str) -> str:
return injected
app = Litestar([index], dependencies={"injected": Provide(my_dependency)})
Middleware
Litestar supports typical ASGI middleware and ships with middlewares to handle things such as
- CORS
- CSRF
- Rate limiting
- GZip and Brotli compression
- Client- and server-side sessions
Route Guards
Litestar has an authorization mechanism called guards
, 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 guards
from litestar import Litestar, get
from litestar.connection import ASGIConnection
from litestar.handlers.base import BaseRouteHandler
from litestar.exceptions import NotAuthorizedException
async def is_authorized(connection: ASGIConnection, handler: BaseRouteHandler) -> None:
# validate authorization
# if not authorized, raise NotAuthorizedException
raise NotAuthorizedException()
@get("/", guards=[is_authorized])
async def index() -> None: ...
app = Litestar([index])
Request Life Cycle Hooks
Litestar supports request life cycle hooks, similarly to Flask - i.e. before_request
and after_request
Performance
Litestar is fast. It is on par with, or significantly faster than comparable ASGI frameworks.
You can see and run the benchmarks here, or read more about it here in our documentation.
Contributing
Litestar is open to contributions big and small. You can always join our discord server or join our Matrix space to discuss contributions and project maintenance. For guidelines on how to contribute, please see the contribution guide.