Debian Codegraph @

examples/fastapi/fastapi_service_full.py

raw
1 # /// script
2 # dependencies = [
3 # "advanced_alchemy",
4 # "aiosqlite",
5 # "fastapi[standard]",
6 # "orjson"
7 # ]
8 # ///
9 import datetime
10 from typing import Annotated, Optional
11 from uuid import UUID
12
13 from fastapi import APIRouter, Depends, FastAPI
14 from pydantic import BaseModel
15 from sqlalchemy import ForeignKey
16 from sqlalchemy.orm import Mapped, mapped_column, relationship
17
18 from advanced_alchemy.extensions.fastapi import (
19 AdvancedAlchemy,
20 AsyncSessionConfig,
21 SQLAlchemyAsyncConfig,
22 base,
23 filters,
24 repository,
25 service,
26 )
27 from advanced_alchemy.utils.serialization import ModelDictT, is_dict, schema_dump
28
29 alchemy_config = SQLAlchemyAsyncConfig(
30 connection_string="sqlite+aiosqlite:///test.sqlite",
31 session_config=AsyncSessionConfig(expire_on_commit=False),
32 commit_mode="autocommit",
33 create_all=True,
34 )
35 app = FastAPI()
36 alchemy = AdvancedAlchemy(config=alchemy_config, app=app)
37 author_router = APIRouter()
38
39
40 class BookModel(base.UUIDAuditBase):
41 __tablename__ = "book"
42 title: Mapped[str]
43 author_id: Mapped[UUID] = mapped_column(ForeignKey("author.id", ondelete="CASCADE"), nullable=False)
44 author: Mapped["AuthorModel"] = relationship(back_populates="books", lazy="joined", innerjoin=True, uselist=False)
45
46
47 class AuthorModel(base.UUIDBase):
48 # we can optionally provide the table name instead of auto-generating it
49 __tablename__ = "author"
50 name: Mapped[str]
51 dob: Mapped[Optional[datetime.date]]
52 books: Mapped[list[BookModel]] = relationship(
53 back_populates="author", lazy="selectin", cascade="all, delete-orphan", uselist=True
54 )
55
56
57 class AuthorService(service.SQLAlchemyAsyncRepositoryService[AuthorModel]):
58 """Author Service."""
59
60 class Repo(repository.SQLAlchemyAsyncRepository[AuthorModel]):
61 """Author repository."""
62
63 model_type = AuthorModel
64
65 repository_type = Repo
66 match_fields = ["name"]
67
68 async def to_model_on_create(self, data: "ModelDictT[AuthorModel]") -> "ModelDictT[AuthorModel]":
69 data = schema_dump(data)
70 return await self._add_books(data)
71
72 async def to_model_on_update(self, data: "ModelDictT[AuthorModel]") -> "ModelDictT[AuthorModel]":
73 data = schema_dump(data)
74 return await self._update_books(data)
75
76 async def _add_books(self, data: "ModelDictT[AuthorModel]") -> "ModelDictT[AuthorModel]":
77 if is_dict(data):
78 books = data.pop("books", None)
79 data = await super().to_model(data)
80 if books is not None:
81 data.books.extend([BookModel(title=book) for book in books])
82 return data
83
84 async def _update_books(self, data: "ModelDictT[AuthorModel]") -> "ModelDictT[AuthorModel]":
85 if is_dict(data):
86 books: list[str] = data.pop("books", [])
87 data = await super().to_model(data)
88 if books:
89 existing_books = [book.title for book in data.books]
90 books_to_remove = [book for book in data.books if book.title not in books]
91 books_to_add = [book for book in books if book not in existing_books]
92
93 # First mark books for deletion
94 for book_rm in books_to_remove:
95 self.repository.session.delete(book_rm)
96 data.books.remove(book_rm)
97
98 # Finally add new books
99 data.books.extend([BookModel(title=book) for book in books_to_add])
100 return data
101
102
103 class AuthorBooks(BaseModel):
104 id: UUID
105 title: str
106
107
108 class Author(BaseModel):
109 id: Optional[UUID]
110 name: str
111 dob: Optional[datetime.date]
112 books: list[AuthorBooks]
113
114
115 class AuthorCreate(BaseModel):
116 name: str
117 dob: Optional[datetime.date] = None
118 books: Optional[list[str]] = None
119
120
121 class AuthorUpdate(BaseModel):
122 name: Optional[str] = None
123 dob: Optional[datetime.date] = None
124 books: Optional[list[str]] = None
125
126
127 @author_router.get(path="/authors", response_model=service.OffsetPagination[Author])
128 async def list_authors(
129 authors_service: Annotated[
130 AuthorService, Depends(alchemy.provide_service(AuthorService, load=[AuthorModel.books]))
131 ],
132 filters: Annotated[
133 list[filters.FilterTypes],
134 Depends(
135 alchemy.provide_filters(
136 {
137 "id_filter": UUID,
138 "pagination_type": "limit_offset",
139 "search": "name",
140 "search_ignore_case": True,
141 }
142 )
143 ),
144 ],
145 ) -> service.OffsetPagination[Author]:
146 results, total = await authors_service.get_many_and_count(*filters)
147 return authors_service.to_schema(results, total, filters=filters, schema_type=Author)
148
149
150 @author_router.post(path="/authors", response_model=Author)
151 async def create_author(
152 authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))],
153 data: AuthorCreate,
154 ) -> AuthorModel:
155 obj = await authors_service.create(data)
156 return authors_service.to_schema(obj)
157
158
159 # we override the authors_repo to use the version that joins the Books in
160 @author_router.get(path="/authors/{author_id}", response_model=Author)
161 async def get_author(
162 authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))],
163 author_id: UUID,
164 ) -> AuthorModel:
165 obj = await authors_service.get(author_id)
166 return authors_service.to_schema(obj)
167
168
169 @author_router.patch(path="/authors/{author_id}", response_model=Author)
170 async def update_author(
171 authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))],
172 data: AuthorUpdate,
173 author_id: UUID,
174 ) -> AuthorModel:
175 obj = await authors_service.update(data, item_id=author_id)
176 return authors_service.to_schema(obj)
177
178
179 @author_router.delete(path="/authors/{author_id}")
180 async def delete_author(
181 authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], author_id: UUID
182 ) -> None:
183 _ = await authors_service.delete(author_id)
184
185
186 app.include_router(author_router)
187
188
189 if __name__ == "__main__":
190 """Launches the FastAPI CLI with the database commands registered
191 Run `uv run examples/fastapi/fastapi_service.py --help` to launch the FastAPI CLI with the database commands registered
192 """
193 from fastapi_cli.cli import app as fastapi_cli_app # pyright: ignore[reportUnknownVariableType]
194
195 from advanced_alchemy.extensions.fastapi import assign_cli_group
196
197 assign_cli_group(app)
198 fastapi_cli_app()