Litestar Integration#
Advanced Alchemy is built by the Litestar team and plugs into Litestar with a single SQLAlchemyPlugin. One plugin setup handles database connections, per-request sessions, JSON serialization, error responses, and litestar database CLI migrations.
What’s Included for Litestar#
Feature |
What It Gives You |
Guide & API |
|---|---|---|
Plugin & Configs |
Starts engines on app startup, opens a session per request, and maps database errors to HTTP responses. |
|
Service & Filter DI |
Injects services and ready-made search/pagination filters straight into controller routes. |
|
SQLAlchemy DTOs |
Auto-generates request/response DTOs from your SQLAlchemy models and |
|
Sessions & Stores |
Connects multiple databases and stores server-side user sessions or cache keys in SQL tables. |
|
File Storage |
Streams |
|
Database CLI |
Adds |
Installation#
uv add "advanced-alchemy[litestar,aiosqlite]"
pip install "advanced-alchemy[litestar,aiosqlite]"
pdm add "advanced-alchemy[litestar,aiosqlite]"
poetry add "advanced-alchemy[litestar,aiosqlite]"
Auto-Generating DTOs from Models#
Don’t want to write separate msgspec or Pydantic schemas for simple CRUD endpoints? SQLAlchemyDTO inspects your model’s columns, relationships, and read-only @property fields automatically:
from functools import cached_property
from sqlalchemy.orm import Mapped
from advanced_alchemy.extensions.litestar import SQLAlchemyDTO, base
class UserAccount(base.UUIDAuditBase):
__tablename__ = "litestar_doc_user_account"
first_name: Mapped[str]
last_name: Mapped[str]
@property
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"
@cached_property
def display_length(self) -> int:
return len(self.full_name)
UserAccountDTO = SQLAlchemyDTO[UserAccount]
Complete Runnable App#
View Complete Litestar Application
"""Basic Litestar application with Advanced Alchemy service, DTO, and controller integration."""
from http import HTTPStatus
from typing import Annotated
from uuid import UUID
import msgspec
from litestar import Controller, Litestar, get, post
from litestar.di import NamedDependency
from litestar.params import SkipValidation
from litestar.testing import TestClient
from sqlalchemy.orm import Mapped
from advanced_alchemy.extensions.litestar import (
SQLAlchemyAsyncConfig,
SQLAlchemyDTO,
SQLAlchemyDTOConfig,
SQLAlchemyPlugin,
base,
filters,
providers,
repository,
service,
)
__all__ = (
"AuthorController",
"AuthorCreate",
"AuthorDTO",
"AuthorModel",
"AuthorRepository",
"AuthorSchema",
"AuthorService",
"AuthorWriteDTO",
"create_app",
"main",
)
class AuthorModel(base.UUIDBase):
"""Author database model."""
__tablename__ = "litestar_basic_author"
name: Mapped[str]
class AuthorCreate(msgspec.Struct):
"""Payload for creating an author."""
name: str
class AuthorSchema(msgspec.Struct):
"""Serialized author schema."""
id: UUID
name: str
AuthorDTO = SQLAlchemyDTO[AuthorModel]
AuthorWriteDTO = SQLAlchemyDTO[
Annotated[
AuthorModel,
SQLAlchemyDTOConfig(exclude={"id"}),
]
]
class AuthorRepository(repository.SQLAlchemyAsyncRepository[AuthorModel]):
"""Author async repository."""
model_type = AuthorModel
class AuthorService(service.SQLAlchemyAsyncRepositoryService[AuthorModel, AuthorRepository]):
"""Author async repository service."""
repository_type = AuthorRepository
class AuthorController(Controller):
"""Author HTTP endpoints."""
path = "/authors"
dependencies = providers.create_service_dependencies(
AuthorService,
"authors_service",
filters={"id_filter": UUID, "search": "name", "pagination_type": "limit_offset"},
)
@post(path="/")
async def create_author(
self,
authors_service: NamedDependency[AuthorService],
data: AuthorCreate,
) -> AuthorSchema:
"""Create a new author record."""
obj = await authors_service.create(data, auto_commit=True)
return authors_service.to_schema(obj, schema_type=AuthorSchema)
@get(path="/")
async def list_authors(
self,
authors_service: NamedDependency[AuthorService],
filters: NamedDependency[SkipValidation[list[filters.FilterTypes]]],
) -> service.OffsetPagination[AuthorSchema]:
"""List authors with standard pagination and filtering."""
results, total = await authors_service.get_many_and_count(*filters)
return authors_service.to_schema(
results,
total,
filters=filters,
schema_type=AuthorSchema,
)
def create_app() -> Litestar:
"""Construct the Litestar application with an in-memory SQLite database."""
return Litestar(
route_handlers=[AuthorController],
plugins=[
SQLAlchemyPlugin(
config=SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///:memory:",
create_all=True,
),
),
],
)
def main() -> None:
"""Execute the basic Litestar application example in-process."""
app = create_app()
with TestClient(app=app) as client:
create_response = client.post("/authors/", json={"name": "Ada Lovelace"})
if create_response.status_code != HTTPStatus.CREATED:
msg = f"Unexpected create status: {create_response.status_code}"
raise RuntimeError(msg)
created = create_response.json()
if created["name"] != "Ada Lovelace":
msg = f"Unexpected created author name: {created['name']}"
raise RuntimeError(msg)
list_response = client.get("/authors/?currentPage=1&pageSize=10")
if list_response.status_code != HTTPStatus.OK:
msg = f"Unexpected list status: {list_response.status_code}"
raise RuntimeError(msg)
payload = list_response.json()
if payload["total"] != 1 or payload["items"][0]["name"] != "Ada Lovelace":
msg = f"Unexpected list payload: {payload}"
raise RuntimeError(msg)
More Litestar Guides#
Litestar Services, Filters and DTOs — Injecting services, OpenAPI query filters, and auto-generated
SQLAlchemyDTOschemas.Litestar Database and Server Sessions — Request transactions, multi-database setups, and server-side session stores.
Litestar File and Object Storage — File uploads and cloud/local object storage.
Litestar SQLAlchemy Docs — Upstream Litestar framework guide.