Working with Controllers and Repositories

We’ve been working our way up the stack, starting with the database models, and now we are ready to use the repository in an actual route. Let’s see how we can use this in a controller.

Tip

The full code for this tutorial can be found below in the Full Code section.

First, we create a simple function that returns an instance of AuthorRepository. This function will be used to inject a repository instance into our controller routes. Note that we are only passing in the database session in this example with no other parameters.

app.py
1async def provide_authors_repo(db_session: NamedDependency[AsyncSession]) -> AuthorRepository:
2    """This provides the default Authors repository."""
3    return AuthorRepository(session=db_session)

Because we’ll be using the SQLAlchemy plugin in Litestar, the session is automatically configured as a dependency.

By default, the repository doesn’t add any additional query options to your base statement, but provides the flexibility to override it, allowing you to pass your own statement:

app.py
1# we can optionally override the default `select` used for the repository to pass in
2# specific SQL options such as join details
3async def provide_author_details_repo(db_session: NamedDependency[AsyncSession]) -> AuthorRepository:
4    """This provides a simple example demonstrating how to override the join options for the repository."""
5    return AuthorRepository(
6        statement=select(AuthorModel).options(selectinload(AuthorModel.books)),
7        session=db_session,
8    )

In this instance, we enhance the repository function by adding a selectinload option. This option configures the specified relationship to load via SELECT .. IN … loading pattern, optimizing the query execution.

Next, we define the AuthorController. This controller exposes five routes for interacting with the Author model:

AuthorController (click to toggle)
app.py
 1class AuthorController(Controller):
 2    """Author CRUD"""
 3
 4    dependencies = {AuthorRepository: provide_authors_repo}
 5
 6    @get(path="/authors")
 7    async def list_authors(
 8        self,
 9        authors_repo: TypeDependency[AuthorRepository],
10        limit_offset: TypeDependency[filters.LimitOffset],
11    ) -> OffsetPagination[Author]:
12        """List authors."""
13        results, total = await authors_repo.list_and_count(limit_offset)
14        type_adapter = TypeAdapter(list[Author])
15        return OffsetPagination[Author](
16            items=type_adapter.validate_python(results),
17            total=total,
18            limit=limit_offset.limit,
19            offset=limit_offset.offset,
20        )
21
22    @post(path="/authors")
23    async def create_author(
24        self,
25        authors_repo: TypeDependency[AuthorRepository],
26        data: JSONBody[AuthorCreate],
27    ) -> Author:
28        """Create a new author."""
29        obj = await authors_repo.add(
30            AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)),
31        )
32        await authors_repo.session.commit()
33        return Author.model_validate(obj)
34
35    # we override the authors_repo to use the version that joins the Books in
36    @get(path="/authors/{author_id:uuid}", dependencies={AuthorRepository: provide_author_details_repo})
37    async def get_author(
38        self,
39        authors_repo: TypeDependency[AuthorRepository],
40        author_id: Annotated[
41            UUID,
42            PathParameter(
43                title="Author ID",
44                description="The author to retrieve.",
45            ),
46        ],
47    ) -> Author:
48        """Get an existing author."""
49        obj = await authors_repo.get(author_id)
50        return Author.model_validate(obj)
51
52    @patch(
53        path="/authors/{author_id:uuid}",
54        dependencies={AuthorRepository: provide_author_details_repo},
55    )
56    async def update_author(
57        self,
58        authors_repo: TypeDependency[AuthorRepository],
59        data: JSONBody[AuthorUpdate],
60        author_id: Annotated[
61            UUID,
62            PathParameter(
63                title="Author ID",
64                description="The author to update.",
65            ),
66        ],
67    ) -> Author:
68        """Update an author."""
69        raw_obj = data.model_dump(exclude_unset=True, exclude_none=True)
70        raw_obj.update({"id": author_id})
71        obj = await authors_repo.update(AuthorModel(**raw_obj))
72        await authors_repo.session.commit()
73        return Author.from_orm(obj)
74
75    @delete(path="/authors/{author_id:uuid}")
76    async def delete_author(
77        self,
78        authors_repo: TypeDependency[AuthorRepository],
79        author_id: Annotated[
80            UUID,
81            PathParameter(
82                title="Author ID",
83                description="The author to delete.",
84            ),
85        ],
86    ) -> None:
87        """Delete a author from the system."""
88        _ = await authors_repo.delete(author_id)
89        await authors_repo.session.commit()

In our list detail endpoint, we use the pagination filter for limiting the amount of data returned, allowing us to retrieve large datasets in smaller, more manageable chunks.

In the above examples, we’ve used the asynchronous repository implementation. However, Litestar also supports synchronous database drivers with an identical implementation. Here’s a corresponding synchronous version of the previous example:

Synchronous Repository (click to toggle)
app.py
  1from __future__ import annotations
  2
  3from datetime import date
  4from typing import TYPE_CHECKING, Annotated
  5from uuid import UUID
  6
  7from advanced_alchemy.extensions.litestar import (
  8    SQLAlchemyInitPlugin,
  9    SQLAlchemySyncConfig,
 10    base,
 11    repository,
 12)
 13from advanced_alchemy.filters import LimitOffset
 14from advanced_alchemy.service import OffsetPagination
 15from pydantic import BaseModel as _BaseModel
 16from pydantic import TypeAdapter
 17from sqlalchemy import ForeignKey, select
 18from sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload
 19
 20from litestar import Litestar, get
 21from litestar.controller import Controller
 22from litestar.di import NamedDependency, TypeDependency, provide
 23from litestar.handlers.http_handlers.decorators import delete, patch, post
 24from litestar.params import JSONBody, PathParameter, QueryParameter
 25
 26if TYPE_CHECKING:
 27    from sqlalchemy.orm import Session
 28
 29
 30class BaseModel(_BaseModel):
 31    """Extend Pydantic's BaseModel to enable ORM mode"""
 32
 33    model_config = {"from_attributes": True}
 34
 35
 36# The SQLAlchemy base includes a declarative model for you to use in your models.
 37# The `UUIDBase` class includes a `UUID` based primary key (`id`)
 38class AuthorModel(base.UUIDBase):
 39    # we can optionally provide the table name instead of auto-generating it
 40    __tablename__ = "author"
 41    name: Mapped[str]
 42    dob: Mapped[date | None]
 43    books: Mapped[list[BookModel]] = relationship(back_populates="author", lazy="noload")
 44
 45
 46# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
 47# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
 48# record created, and `updated_at` is the last time the record was modified.
 49class BookModel(base.UUIDAuditBase):
 50    __tablename__ = "book"
 51    title: Mapped[str]
 52    author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
 53    author: Mapped[AuthorModel] = relationship(lazy="joined", innerjoin=True, viewonly=True)
 54
 55
 56# we will explicitly define the schema instead of using DTO objects for clarity.
 57
 58
 59class Author(BaseModel):
 60    id: UUID | None
 61    name: str
 62    dob: date | None = None
 63
 64
 65class AuthorCreate(BaseModel):
 66    name: str
 67    dob: date | None = None
 68
 69
 70class AuthorUpdate(BaseModel):
 71    name: str | None = None
 72    dob: date | None = None
 73
 74
 75class AuthorRepository(repository.SQLAlchemySyncRepository[AuthorModel]):
 76    """Author repository."""
 77
 78    model_type = AuthorModel
 79
 80
 81async def provide_authors_repo(db_session: NamedDependency[Session]) -> AuthorRepository:
 82    """This provides the default Authors repository."""
 83    return AuthorRepository(session=db_session)
 84
 85
 86# we can optionally override the default `select` used for the repository to pass in
 87# specific SQL options such as join details
 88async def provide_author_details_repo(db_session: NamedDependency[Session]) -> AuthorRepository:
 89    """This provides a simple example demonstrating how to override the join options
 90    for the repository."""
 91    return AuthorRepository(
 92        statement=select(AuthorModel).options(selectinload(AuthorModel.books)),
 93        session=db_session,
 94    )
 95
 96
 97@provide(kind="type", sync_to_thread=False)
 98def provide_limit_offset_pagination(
 99    current_page: Annotated[int, QueryParameter(name="currentPage", ge=1, required=False)] = 1,
100    page_size: Annotated[int, QueryParameter(name="pageSize", ge=1, required=False)] = 10,
101) -> LimitOffset:
102    """Add offset/limit pagination.
103
104    Return type consumed by `Repository.apply_limit_offset_pagination()`.
105
106    Parameters
107    ----------
108    current_page : int
109        LIMIT to apply to select.
110    page_size : int
111        OFFSET to apply to select.
112    """
113    return LimitOffset(page_size, page_size * (current_page - 1))
114
115
116class AuthorController(Controller):
117    """Author CRUD"""
118
119    dependencies = {AuthorRepository: provide_authors_repo}
120
121    @get(path="/authors")
122    def list_authors(
123        self,
124        authors_repo: TypeDependency[AuthorRepository],
125        limit_offset: TypeDependency[LimitOffset],
126    ) -> OffsetPagination[Author]:
127        """List authors."""
128        results, total = authors_repo.list_and_count(limit_offset)
129        type_adapter = TypeAdapter(list[Author])
130        return OffsetPagination[Author](
131            items=type_adapter.validate_python(results),
132            total=total,
133            limit=limit_offset.limit,
134            offset=limit_offset.offset,
135        )
136
137    @post(path="/authors")
138    def create_author(
139        self,
140        authors_repo: TypeDependency[AuthorRepository],
141        data: JSONBody[AuthorCreate],
142    ) -> Author:
143        """Create a new author."""
144        obj = authors_repo.add(
145            AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)),
146        )
147        authors_repo.session.commit()
148        return Author.model_validate(obj)
149
150    # we override the authors_repo to use the version that joins the Books in
151    @get(
152        path="/authors/{author_id:uuid}",
153        dependencies={AuthorRepository: provide_author_details_repo},
154    )
155    def get_author(
156        self,
157        authors_repo: TypeDependency[AuthorRepository],
158        author_id: Annotated[
159            UUID,
160            PathParameter(
161                title="Author ID",
162                description="The author to retrieve.",
163            ),
164        ],
165    ) -> Author:
166        """Get an existing author."""
167        obj = authors_repo.get(author_id)
168        return Author.model_validate(obj)
169
170    @patch(
171        path="/authors/{author_id:uuid}",
172        dependencies={AuthorRepository: provide_author_details_repo},
173    )
174    def update_author(
175        self,
176        authors_repo: TypeDependency[AuthorRepository],
177        data: JSONBody[AuthorUpdate],
178        author_id: Annotated[
179            UUID,
180            PathParameter(
181                title="Author ID",
182                description="The author to update.",
183            ),
184        ],
185    ) -> Author:
186        """Update an author."""
187        raw_obj = data.model_dump(exclude_unset=True, exclude_none=True)
188        raw_obj.update({"id": author_id})
189        obj = authors_repo.update(AuthorModel(**raw_obj))
190        authors_repo.session.commit()
191        return Author.model_validate(obj)
192
193    @delete(path="/authors/{author_id:uuid}")
194    def delete_author(
195        self,
196        authors_repo: TypeDependency[AuthorRepository],
197        author_id: Annotated[
198            UUID,
199            PathParameter(
200                title="Author ID",
201                description="The author to delete.",
202            ),
203        ],
204    ) -> None:
205        """Delete a author from the system."""
206        _ = authors_repo.delete(author_id)
207        authors_repo.session.commit()
208
209
210sqlalchemy_config = SQLAlchemySyncConfig(connection_string="sqlite:///test.sqlite")  # Create 'db_session' dependency.
211sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
212
213
214def on_startup() -> None:
215    """Initializes the database."""
216    with sqlalchemy_config.get_engine().begin() as conn:
217        base.UUIDBase.metadata.create_all(conn)
218
219
220app = Litestar(
221    route_handlers=[AuthorController],
222    on_startup=[on_startup],
223    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
224    dependencies=[provide_limit_offset_pagination],
225)

The examples above enable a feature-complete CRUD service that includes pagination! In the next section, we’ll explore how to extend the built-in repository to add additional functionality to our application.

Full Code

Full Code (click to toggle)
app.py
  1from __future__ import annotations
  2
  3from datetime import date
  4from typing import TYPE_CHECKING, Annotated
  5from uuid import UUID
  6
  7from advanced_alchemy.extensions.litestar import (
  8    AsyncSessionConfig,
  9    SQLAlchemyAsyncConfig,
 10    SQLAlchemyInitPlugin,
 11    base,
 12    filters,
 13    repository,
 14)
 15from advanced_alchemy.service import OffsetPagination
 16from pydantic import BaseModel as _BaseModel
 17from pydantic import TypeAdapter
 18from sqlalchemy import ForeignKey, select
 19from sqlalchemy.orm import Mapped, mapped_column, relationship, selectinload
 20
 21from litestar import Litestar, get
 22from litestar.controller import Controller
 23from litestar.di import NamedDependency, TypeDependency, provide
 24from litestar.handlers.http_handlers.decorators import delete, patch, post
 25from litestar.params import JSONBody, PathParameter, QueryParameter
 26
 27if TYPE_CHECKING:
 28    from sqlalchemy.ext.asyncio import AsyncSession
 29
 30
 31class BaseModel(_BaseModel):
 32    """Extend Pydantic's BaseModel to enable ORM mode"""
 33
 34    model_config = {"from_attributes": True}
 35
 36
 37# The SQLAlchemy base includes a declarative model for you to use in your models.
 38# The `UUIDBase` class includes a `UUID` based primary key (`id`)
 39class AuthorModel(base.UUIDBase):
 40    # we can optionally provide the table name instead of auto-generating it
 41    __tablename__ = "author"
 42    name: Mapped[str]
 43    dob: Mapped[date | None]
 44    books: Mapped[list[BookModel]] = relationship(back_populates="author", lazy="noload")
 45
 46
 47# The `UUIDAuditBase` class includes the same UUID` based primary key (`id`) and 2
 48# additional columns: `created_at` and `updated_at`. `created_at` is a timestamp of when the
 49# record created, and `updated_at` is the last time the record was modified.
 50class BookModel(base.UUIDAuditBase):
 51    __tablename__ = "book"
 52    title: Mapped[str]
 53    author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id"))
 54    author: Mapped[AuthorModel] = relationship(lazy="joined", innerjoin=True, viewonly=True)
 55
 56
 57# we will explicitly define the schema instead of using DTO objects for clarity.
 58
 59
 60class Author(BaseModel):
 61    id: UUID | None
 62    name: str
 63    dob: date | None = None
 64
 65
 66class AuthorCreate(BaseModel):
 67    name: str
 68    dob: date | None = None
 69
 70
 71class AuthorUpdate(BaseModel):
 72    name: str | None = None
 73    dob: date | None = None
 74
 75
 76class AuthorRepository(repository.SQLAlchemyAsyncRepository[AuthorModel]):
 77    """Author repository."""
 78
 79    model_type = AuthorModel
 80
 81
 82async def provide_authors_repo(db_session: NamedDependency[AsyncSession]) -> AuthorRepository:
 83    """This provides the default Authors repository."""
 84    return AuthorRepository(session=db_session)
 85
 86
 87# we can optionally override the default `select` used for the repository to pass in
 88# specific SQL options such as join details
 89async def provide_author_details_repo(db_session: NamedDependency[AsyncSession]) -> AuthorRepository:
 90    """This provides a simple example demonstrating how to override the join options for the repository."""
 91    return AuthorRepository(
 92        statement=select(AuthorModel).options(selectinload(AuthorModel.books)),
 93        session=db_session,
 94    )
 95
 96
 97@provide(kind="type", sync_to_thread=False)
 98def provide_limit_offset_pagination(
 99    current_page: Annotated[int, QueryParameter(name="currentPage", ge=1, required=False)] = 1,
100    page_size: Annotated[int, QueryParameter(name="pageSize", ge=1, required=False)] = 10,
101) -> filters.LimitOffset:
102    """Add offset/limit pagination.
103
104    Return type consumed by `Repository.apply_limit_offset_pagination()`.
105
106    Parameters
107    ----------
108    current_page : int
109        LIMIT to apply to select.
110    page_size : int
111        OFFSET to apply to select.
112    """
113    return filters.LimitOffset(page_size, page_size * (current_page - 1))
114
115
116class AuthorController(Controller):
117    """Author CRUD"""
118
119    dependencies = {AuthorRepository: provide_authors_repo}
120
121    @get(path="/authors")
122    async def list_authors(
123        self,
124        authors_repo: TypeDependency[AuthorRepository],
125        limit_offset: TypeDependency[filters.LimitOffset],
126    ) -> OffsetPagination[Author]:
127        """List authors."""
128        results, total = await authors_repo.list_and_count(limit_offset)
129        type_adapter = TypeAdapter(list[Author])
130        return OffsetPagination[Author](
131            items=type_adapter.validate_python(results),
132            total=total,
133            limit=limit_offset.limit,
134            offset=limit_offset.offset,
135        )
136
137    @post(path="/authors")
138    async def create_author(
139        self,
140        authors_repo: TypeDependency[AuthorRepository],
141        data: JSONBody[AuthorCreate],
142    ) -> Author:
143        """Create a new author."""
144        obj = await authors_repo.add(
145            AuthorModel(**data.model_dump(exclude_unset=True, exclude_none=True)),
146        )
147        await authors_repo.session.commit()
148        return Author.model_validate(obj)
149
150    # we override the authors_repo to use the version that joins the Books in
151    @get(path="/authors/{author_id:uuid}", dependencies={AuthorRepository: provide_author_details_repo})
152    async def get_author(
153        self,
154        authors_repo: TypeDependency[AuthorRepository],
155        author_id: Annotated[
156            UUID,
157            PathParameter(
158                title="Author ID",
159                description="The author to retrieve.",
160            ),
161        ],
162    ) -> Author:
163        """Get an existing author."""
164        obj = await authors_repo.get(author_id)
165        return Author.model_validate(obj)
166
167    @patch(
168        path="/authors/{author_id:uuid}",
169        dependencies={AuthorRepository: provide_author_details_repo},
170    )
171    async def update_author(
172        self,
173        authors_repo: TypeDependency[AuthorRepository],
174        data: JSONBody[AuthorUpdate],
175        author_id: Annotated[
176            UUID,
177            PathParameter(
178                title="Author ID",
179                description="The author to update.",
180            ),
181        ],
182    ) -> Author:
183        """Update an author."""
184        raw_obj = data.model_dump(exclude_unset=True, exclude_none=True)
185        raw_obj.update({"id": author_id})
186        obj = await authors_repo.update(AuthorModel(**raw_obj))
187        await authors_repo.session.commit()
188        return Author.from_orm(obj)
189
190    @delete(path="/authors/{author_id:uuid}")
191    async def delete_author(
192        self,
193        authors_repo: TypeDependency[AuthorRepository],
194        author_id: Annotated[
195            UUID,
196            PathParameter(
197                title="Author ID",
198                description="The author to delete.",
199            ),
200        ],
201    ) -> None:
202        """Delete a author from the system."""
203        _ = await authors_repo.delete(author_id)
204        await authors_repo.session.commit()
205
206
207session_config = AsyncSessionConfig(expire_on_commit=False)
208sqlalchemy_config = SQLAlchemyAsyncConfig(
209    connection_string="sqlite+aiosqlite:///test.sqlite", session_config=session_config
210)  # Create 'db_session' dependency.
211sqlalchemy_plugin = SQLAlchemyInitPlugin(config=sqlalchemy_config)
212
213
214async def on_startup() -> None:
215    """Initializes the database."""
216    async with sqlalchemy_config.get_engine().begin() as conn:
217        await conn.run_sync(base.UUIDBase.metadata.create_all)
218
219
220app = Litestar(
221    route_handlers=[AuthorController],
222    on_startup=[on_startup],
223    plugins=[SQLAlchemyInitPlugin(config=sqlalchemy_config)],
224    dependencies=[provide_limit_offset_pagination],
225)