FastAPI Services and Filter Depends#

The AdvancedAlchemy extension builds FastAPI Depends(...) providers for SQLAlchemy sessions, services, and OpenAPI-documented pagination, search, sort, and date-range query filters.

Injecting Sessions and Services#

Use alchemy.provide_session() to inject a SQLAlchemy session directly, or alchemy.provide_service(ServiceClass) to inject a bound service instance:

from typing import Annotated
from fastapi import Depends, FastAPI
from sqlalchemy.orm import Mapped
from advanced_alchemy.extensions.fastapi import (
    AdvancedAlchemy,
    AsyncSessionConfig,
    SQLAlchemyAsyncConfig,
    base,
    repository,
    service,
)


class AuthorModel(base.UUIDBase):
    __tablename__ = "fastapi_dep_author"
    name: Mapped[str]


class AuthorRepository(repository.SQLAlchemyAsyncRepository[AuthorModel]):
    model_type = AuthorModel


class AuthorService(service.SQLAlchemyAsyncRepositoryService[AuthorModel, AuthorRepository]):
    repository_type = AuthorRepository


app = FastAPI()
alchemy = AdvancedAlchemy(
    config=SQLAlchemyAsyncConfig(
        connection_string="sqlite+aiosqlite:///:memory:",
        session_config=AsyncSessionConfig(expire_on_commit=False),
        commit_mode="autocommit",
        create_all=True,
    ),
    app=app,
)

AuthorsServiceDep = Annotated[AuthorService, Depends(alchemy.provide_service(AuthorService))]
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession


async def provide_custom_authors(
    db_session: Annotated[AsyncSession, Depends(alchemy.provide_session())],
) -> AsyncGenerator[AuthorService, None]:
    async with AuthorService.new(session=db_session) as authors_service:
        yield authors_service
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession


async def provide_custom_authors(
    db_session: Annotated[AsyncSession, Depends(alchemy.provide_session())],
) -> AsyncGenerator[AuthorService]:
    async with AuthorService.new(session=db_session) as authors_service:
        yield authors_service

Adding Search and Pagination to Swagger UI#

Pass a FilterConfig dictionary to alchemy.provide_filters(...) to generate FastAPI Depends parameters for pagination, text search, sorting, and date filters:

from uuid import UUID
from advanced_alchemy.extensions.fastapi import filters

AuthorFiltersDep = Annotated[
    list[filters.FilterTypes],
    Depends(
        alchemy.provide_filters(
            {
                "id_filter": UUID,
                "search": "name",
                "search_ignore_case": True,
                "pagination_type": "limit_offset",
                "pagination_size": 20,
                "sort_field": "name",
                "created_at": True,
            }
        )
    ),
]


@app.get("/authors")
async def list_authors(
    authors_service: AuthorsServiceDep,
    filters: AuthorFiltersDep,
) -> dict[str, int]:
    _, total = await authors_service.get_many_and_count(*filters)
    return {"total": total}