| 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.orm import Mapped |
| 16 |
|
| 17 |
from advanced_alchemy.extensions.fastapi import ( |
| 18 |
AdvancedAlchemy, |
| 19 |
AsyncSessionConfig, |
| 20 |
SQLAlchemyAsyncConfig, |
| 21 |
base, |
| 22 |
filters, |
| 23 |
repository, |
| 24 |
service, |
| 25 |
) |
| 26 |
|
| 27 |
alchemy_config = SQLAlchemyAsyncConfig( |
| 28 |
connection_string="sqlite+aiosqlite:///test.sqlite", |
| 29 |
session_config=AsyncSessionConfig(expire_on_commit=False), |
| 30 |
commit_mode="autocommit", |
| 31 |
create_all=True, |
| 32 |
) |
| 33 |
app = FastAPI() |
| 34 |
alchemy = AdvancedAlchemy(config=alchemy_config, app=app) |
| 35 |
author_router = APIRouter() |
| 36 |
|
| 37 |
|
| 38 |
# the SQLAlchemy base includes a declarative model for you to use in your models. |
| 39 |
# The `Base` class includes a `UUID` based primary key (`id`) |
| 40 |
class AuthorModel(base.UUIDBase): |
| 41 |
# we can optionally provide the table name instead of auto-generating it |
| 42 |
__tablename__ = "author" |
| 43 |
name: Mapped[str] |
| 44 |
dob: Mapped[Optional[datetime.date]] |
| 45 |
|
| 46 |
|
| 47 |
class AuthorService(service.SQLAlchemyAsyncRepositoryService[AuthorModel]): |
| 48 |
"""Author repository.""" |
| 49 |
|
| 50 |
class Repo(repository.SQLAlchemyAsyncRepository[AuthorModel]): |
| 51 |
"""Author repository.""" |
| 52 |
|
| 53 |
model_type = AuthorModel |
| 54 |
|
| 55 |
repository_type = Repo |
| 56 |
|
| 57 |
|
| 58 |
# Pydantic Models |
| 59 |
class Author(BaseModel): |
| 60 |
id: Optional[UUID] |
| 61 |
name: str |
| 62 |
dob: Optional[datetime.date] |
| 63 |
|
| 64 |
|
| 65 |
class AuthorCreate(BaseModel): |
| 66 |
name: str |
| 67 |
dob: Optional[datetime.date] |
| 68 |
|
| 69 |
|
| 70 |
class AuthorUpdate(BaseModel): |
| 71 |
name: Optional[str] |
| 72 |
dob: Optional[datetime.date] |
| 73 |
|
| 74 |
|
| 75 |
@author_router.get(path="/authors", response_model=service.OffsetPagination[Author]) |
| 76 |
async def list_authors( |
| 77 |
authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], |
| 78 |
filters: Annotated[ |
| 79 |
list[filters.FilterTypes], |
| 80 |
Depends( |
| 81 |
alchemy.provide_filters( |
| 82 |
{ |
| 83 |
"id_filter": UUID, |
| 84 |
"pagination_type": "limit_offset", |
| 85 |
"search": "name", |
| 86 |
"search_ignore_case": True, |
| 87 |
"sort_field": "dob", |
| 88 |
"sort_order": "desc", |
| 89 |
} |
| 90 |
) |
| 91 |
), |
| 92 |
], |
| 93 |
) -> service.OffsetPagination[AuthorModel]: |
| 94 |
results, total = await authors_service.get_many_and_count(*filters) |
| 95 |
return authors_service.to_schema(results, total, filters=filters) |
| 96 |
|
| 97 |
|
| 98 |
@author_router.post(path="/authors") |
| 99 |
async def create_author( |
| 100 |
authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], |
| 101 |
data: AuthorCreate, |
| 102 |
) -> Author: |
| 103 |
obj = await authors_service.create(data) |
| 104 |
# if you want to have the service return a pydantic model instead of the sqlalchemy model, |
| 105 |
# you can do so by passing the model to the schema_type argument of the to_schema method |
| 106 |
return authors_service.to_schema(obj, schema_type=Author) |
| 107 |
|
| 108 |
|
| 109 |
@author_router.get(path="/authors/{author_id}", response_model=Author) |
| 110 |
async def get_author( |
| 111 |
authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], |
| 112 |
author_id: UUID, |
| 113 |
) -> AuthorModel: |
| 114 |
obj = await authors_service.get(author_id) |
| 115 |
return authors_service.to_schema(obj) |
| 116 |
|
| 117 |
|
| 118 |
@author_router.patch(path="/authors/{author_id}", response_model=Author) |
| 119 |
async def update_author( |
| 120 |
authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], |
| 121 |
data: AuthorUpdate, |
| 122 |
author_id: UUID, |
| 123 |
) -> AuthorModel: |
| 124 |
obj = await authors_service.update(data, item_id=author_id) |
| 125 |
return authors_service.to_schema(obj) |
| 126 |
|
| 127 |
|
| 128 |
@author_router.delete(path="/authors/{author_id}") |
| 129 |
async def delete_author( |
| 130 |
authors_service: Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))], author_id: UUID |
| 131 |
) -> None: |
| 132 |
_ = await authors_service.delete(author_id) |
| 133 |
|
| 134 |
|
| 135 |
app.include_router(author_router) |
| 136 |
|
| 137 |
|
| 138 |
if __name__ == "__main__": |
| 139 |
"""Launches the FastAPI CLI with the database commands registered |
| 140 |
Run `uv run examples/fastapi/fastapi_service.py --help` to launch the FastAPI CLI with the database commands registered |
| 141 |
""" |
| 142 |
from fastapi_cli.cli import app as fastapi_cli_app # pyright: ignore[reportUnknownVariableType] |
| 143 |
|
| 144 |
from advanced_alchemy.extensions.fastapi import assign_cli_group |
| 145 |
|
| 146 |
assign_cli_group(app) |
| 147 |
fastapi_cli_app() |