| 1 |
# /// script |
| 2 |
# dependencies = [ |
| 3 |
# "advanced_alchemy", |
| 4 |
# "fastapi[standard]", |
| 5 |
# "orjson" |
| 6 |
# ] |
| 7 |
# /// |
| 8 |
import datetime |
| 9 |
from typing import Annotated, Optional |
| 10 |
from uuid import UUID |
| 11 |
|
| 12 |
from fastapi import APIRouter, Depends, FastAPI |
| 13 |
from pydantic import BaseModel |
| 14 |
from sqlalchemy.orm import Mapped |
| 15 |
|
| 16 |
from advanced_alchemy.extensions.fastapi import ( |
| 17 |
AdvancedAlchemy, |
| 18 |
AsyncSessionConfig, |
| 19 |
SQLAlchemyAsyncConfig, |
| 20 |
base, |
| 21 |
filters, |
| 22 |
repository, |
| 23 |
service, |
| 24 |
) |
| 25 |
|
| 26 |
alchemy_config = SQLAlchemyAsyncConfig( |
| 27 |
connection_string="sqlite+aiosqlite:///test.sqlite", |
| 28 |
session_config=AsyncSessionConfig(expire_on_commit=False), |
| 29 |
create_all=True, |
| 30 |
) |
| 31 |
app = FastAPI() |
| 32 |
alchemy = AdvancedAlchemy(config=alchemy_config, app=app) |
| 33 |
author_router = APIRouter() |
| 34 |
|
| 35 |
|
| 36 |
class AuthorModel(base.UUIDBase): |
| 37 |
__tablename__ = "author" |
| 38 |
name: Mapped[str] |
| 39 |
dob: Mapped[Optional[datetime.date]] |
| 40 |
|
| 41 |
|
| 42 |
class Author(BaseModel): |
| 43 |
id: Optional[UUID] |
| 44 |
name: str |
| 45 |
dob: Optional[datetime.date] |
| 46 |
|
| 47 |
|
| 48 |
class AuthorService(service.SQLAlchemyAsyncRepositoryService[AuthorModel]): |
| 49 |
"""Author repository.""" |
| 50 |
|
| 51 |
class Repo(repository.SQLAlchemyAsyncRepository[AuthorModel]): |
| 52 |
"""Author repository.""" |
| 53 |
|
| 54 |
model_type = AuthorModel |
| 55 |
|
| 56 |
repository_type = Repo |
| 57 |
|
| 58 |
|
| 59 |
@author_router.get(path="/authors", response_model=service.OffsetPagination[Author]) |
| 60 |
async def list_authors( |
| 61 |
authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], |
| 62 |
filters: Annotated[ |
| 63 |
list[filters.FilterTypes], |
| 64 |
Depends( |
| 65 |
alchemy.provide_filters( |
| 66 |
{ |
| 67 |
"id_filter": UUID, |
| 68 |
"pagination_type": "limit_offset", |
| 69 |
"search": "name", |
| 70 |
"search_ignore_case": True, |
| 71 |
} |
| 72 |
) |
| 73 |
), |
| 74 |
], |
| 75 |
) -> service.OffsetPagination[AuthorModel]: |
| 76 |
results, total = await authors_service.get_many_and_count(*filters) |
| 77 |
return authors_service.to_schema(results, total, filters=filters) |
| 78 |
|
| 79 |
|
| 80 |
app.include_router(author_router) |
| 81 |
|
| 82 |
|
| 83 |
if __name__ == "__main__": |
| 84 |
"""Launches the FastAPI CLI with the database commands registered |
| 85 |
Run `uv run examples/fastapi/fastapi_service.py` to launch the FastAPI CLI with the database commands registered |
| 86 |
""" |
| 87 |
from fastapi_cli.cli import app as fastapi_cli_app # pyright: ignore[reportUnknownVariableType] |
| 88 |
|
| 89 |
from advanced_alchemy.extensions.fastapi import assign_cli_group |
| 90 |
|
| 91 |
assign_cli_group(app) |
| 92 |
fastapi_cli_app() |