{"config":{"separator":"[\\s\\-_,:!=\\[\\]()\\\\\"`/]+|\\.(?!\\d)"},"items":[{"location":"","level":1,"title":"FastAPI Toolsets","text":"
A modular collection of production-ready utilities for FastAPI. Install only what you need — from async CRUD and database helpers to CLI tooling, Prometheus metrics, and pytest fixtures. Each module is independently installable via optional extras, keeping your dependency footprint minimal.
Documentation: https://fastapi-toolsets.d3vyce.fr
Source Code: https://github.com/d3vyce/fastapi-toolsets
","path":["FastAPI Toolsets"],"tags":[]},{"location":"#installation","level":2,"title":"Installation","text":"The base package includes the core modules (CRUD, database, schemas, exceptions, fixtures, dependencies, model mixins, logging):
uv add fastapi-toolsets\n Install only the extras you need:
uv add \"fastapi-toolsets[cli]\"\nuv add \"fastapi-toolsets[metrics]\"\nuv add \"fastapi-toolsets[pytest]\"\n Or install everything:
uv add \"fastapi-toolsets[all]\"\n","path":["FastAPI Toolsets"],"tags":[]},{"location":"#features","level":2,"title":"Features","text":"","path":["FastAPI Toolsets"],"tags":[]},{"location":"#core","level":3,"title":"Core","text":"CrudFactory, built-in full-text/faceted search and Offset/Cursor pagination.PathDependency, BodyDependency) for automatic DB lookups from path or body parametersUUIDMixin, UUIDv7Mixin, CreatedAtMixin, UpdatedAtMixin, TimestampMixin) and lifecycle callbacks (WatchedFieldsMixin) that fire after commit for insert, update, and delete events.Response, ErrorResponse, PaginatedResponse, CursorPaginatedResponse and OffsetPaginatedResponse.configure_logging and get_loggerpytest-xdist support, and table cleanup utilitiesMIT License - see LICENSE for details.
","path":["FastAPI Toolsets"],"tags":[]},{"location":"#contributing","level":2,"title":"Contributing","text":"Contributions are welcome! Please feel free to submit issues and pull requests.
","path":["FastAPI Toolsets"],"tags":[]},{"location":"examples/pagination-search/","level":1,"title":"Pagination & search","text":"This example builds an articles listing endpoint that supports offset pagination, cursor pagination, full-text search, faceted filtering, and sorting — all from a single CrudFactory definition.
import uuid\n\nfrom sqlalchemy import Boolean, ForeignKey, String, Text\nfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship\n\nfrom fastapi_toolsets.models import CreatedAtMixin\n\n\nclass Base(DeclarativeBase):\n pass\n\n\nclass Category(Base):\n __tablename__ = \"categories\"\n\n id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)\n name: Mapped[str] = mapped_column(String(64), unique=True)\n\n articles: Mapped[list[\"Article\"]] = relationship(back_populates=\"category\")\n\n\nclass Article(Base, CreatedAtMixin):\n __tablename__ = \"articles\"\n\n id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)\n title: Mapped[str] = mapped_column(String(256))\n body: Mapped[str] = mapped_column(Text)\n status: Mapped[str] = mapped_column(String(32))\n published: Mapped[bool] = mapped_column(Boolean, default=False)\n category_id: Mapped[uuid.UUID | None] = mapped_column(\n ForeignKey(\"categories.id\"), nullable=True\n )\n\n category: Mapped[\"Category | None\"] = relationship(back_populates=\"articles\")\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#schemas","level":2,"title":"Schemas","text":"schemas.pyimport datetime\nimport uuid\n\nfrom fastapi_toolsets.schemas import PydanticBase\n\n\nclass ArticleRead(PydanticBase):\n id: uuid.UUID\n created_at: datetime.datetime\n title: str\n status: str\n published: bool\n category_id: uuid.UUID | None\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#crud","level":2,"title":"Crud","text":"Declare searchable_fields, facet_fields, and order_fields once on CrudFactory. All endpoints built from this class share the same defaults and can override them per call.
from fastapi_toolsets.crud import CrudFactory\n\nfrom .models import Article, Category\n\nArticleCrud = CrudFactory(\n model=Article,\n cursor_column=Article.created_at,\n searchable_fields=[ # default fields for full-text search\n Article.title,\n Article.body,\n (Article.category, Category.name),\n ],\n facet_fields=[ # fields exposed as filter dropdowns\n Article.status,\n (Article.category, Category.name),\n ],\n order_fields=[ # fields exposed for client-driven ordering\n Article.title,\n Article.created_at,\n ],\n)\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#session-dependency","level":2,"title":"Session dependency","text":"db.pyfrom typing import Annotated\n\nfrom fastapi import Depends\nfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine\n\nfrom fastapi_toolsets.db import create_db_context, create_db_dependency\n\nDATABASE_URL = \"postgresql+asyncpg://postgres:postgres@localhost:5432/postgres\"\n\nengine = create_async_engine(url=DATABASE_URL, future=True)\nasync_session_maker = async_sessionmaker(bind=engine, expire_on_commit=False)\n\nget_db = create_db_dependency(session_maker=async_session_maker)\nget_db_context = create_db_context(session_maker=async_session_maker)\n\n\nSessionDep = Annotated[AsyncSession, Depends(get_db)]\n Deploy a Postgres DB with docker
docker run -d --name postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres -p 5432:5432 postgres:18-alpine\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#app","level":2,"title":"App","text":"app.pyfrom fastapi import FastAPI\n\nfrom fastapi_toolsets.exceptions import init_exceptions_handlers\n\nfrom .routes import router\n\napp = FastAPI()\ninit_exceptions_handlers(app=app)\napp.include_router(router=router)\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#routes","level":2,"title":"Routes","text":"routes.py:1:17from typing import Annotated\n\nfrom fastapi import APIRouter, Depends\n\nfrom fastapi_toolsets.crud import OrderByClause\nfrom fastapi_toolsets.schemas import (\n CursorPaginatedResponse,\n OffsetPaginatedResponse,\n PaginatedResponse,\n)\n\nfrom .crud import ArticleCrud\nfrom .db import SessionDep\nfrom .models import Article\nfrom .schemas import ArticleRead\n\nrouter = APIRouter(prefix=\"/articles\")\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#offset-pagination","level":3,"title":"Offset pagination","text":"Best for admin panels or any UI that needs a total item count and numbered pages.
routes.py:20:40@router.get(\"/offset\")\nasync def list_articles_offset(\n session: SessionDep,\n params: Annotated[\n dict,\n Depends(ArticleCrud.offset_params(default_page_size=20, max_page_size=100)),\n ],\n filter_by: Annotated[dict[str, list[str]], Depends(ArticleCrud.filter_params())],\n order_by: Annotated[\n OrderByClause | None,\n Depends(ArticleCrud.order_params(default_field=Article.created_at)),\n ],\n search: str | None = None,\n) -> OffsetPaginatedResponse[ArticleRead]:\n return await ArticleCrud.offset_paginate(\n session=session,\n **params,\n search=search,\n filter_by=filter_by or None,\n order_by=order_by,\n schema=ArticleRead,\n Example request
GET /articles/offset?page=2&items_per_page=10&search=fastapi&status=published&order_by=title&order=asc\n Example response
{\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"offset\",\n \"data\": [\n { \"id\": \"3f47ac69-...\", \"title\": \"FastAPI tips\", \"status\": \"published\", ... }\n ],\n \"pagination\": {\n \"total_count\": 42,\n \"pages\": 5,\n \"page\": 2,\n \"items_per_page\": 10,\n \"has_more\": true\n },\n \"filter_attributes\": {\n \"status\": [\"archived\", \"draft\", \"published\"],\n \"name\": [\"backend\", \"frontend\", \"python\"]\n }\n}\n filter_attributes always reflects the values visible after applying the active filters. Use it to populate filter dropdowns on the client.
To skip the COUNT(*) query for better performance on large tables, pass include_total=False. pagination.total_count will be null in the response, while has_more remains accurate.
Best for feeds, infinite scroll, or any high-throughput API where offset performance degrades.
routes.py:43:63@router.get(\"/cursor\")\nasync def list_articles_cursor(\n session: SessionDep,\n params: Annotated[\n dict,\n Depends(ArticleCrud.cursor_params(default_page_size=20, max_page_size=100)),\n ],\n filter_by: Annotated[dict[str, list[str]], Depends(ArticleCrud.filter_params())],\n order_by: Annotated[\n OrderByClause | None,\n Depends(ArticleCrud.order_params(default_field=Article.created_at)),\n ],\n search: str | None = None,\n) -> CursorPaginatedResponse[ArticleRead]:\n return await ArticleCrud.cursor_paginate(\n session=session,\n **params,\n search=search,\n filter_by=filter_by or None,\n order_by=order_by,\n Example request
GET /articles/cursor?items_per_page=10&status=published&order_by=created_at&order=desc\n Example response
{\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"cursor\",\n \"data\": [\n { \"id\": \"3f47ac69-...\", \"title\": \"FastAPI tips\", \"status\": \"published\", ... }\n ],\n \"pagination\": {\n \"next_cursor\": \"eyJ2YWx1ZSI6ICIzZjQ3YWM2OS0uLi4ifQ==\",\n \"prev_cursor\": null,\n \"items_per_page\": 10,\n \"has_more\": true\n },\n \"filter_attributes\": {\n \"status\": [\"published\"],\n \"name\": [\"backend\", \"python\"]\n }\n}\n Pass next_cursor as the cursor query parameter on the next request to advance to the next page.
Added in v2.3.0
paginate() lets a single endpoint support both strategies via a pagination_type query parameter. The pagination_type field in the response acts as a discriminator for frontend tooling.
@router.get(\"/\")\nasync def list_articles(\n session: SessionDep,\n params: Annotated[\n dict,\n Depends(ArticleCrud.paginate_params(default_page_size=20, max_page_size=100)),\n ],\n filter_by: Annotated[dict[str, list[str]], Depends(ArticleCrud.filter_params())],\n order_by: Annotated[\n OrderByClause | None,\n Depends(ArticleCrud.order_params(default_field=Article.created_at)),\n ],\n search: str | None = None,\n) -> PaginatedResponse[ArticleRead]:\n return await ArticleCrud.paginate(\n session,\n **params,\n search=search,\n filter_by=filter_by or None,\n order_by=order_by,\n schema=ArticleRead,\n )\n Offset request (default)
GET /articles/?pagination_type=offset&page=1&items_per_page=10\n {\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"offset\",\n \"data\": [\"...\"],\n \"pagination\": { \"total_count\": 42, \"pages\": 5, \"page\": 1, \"items_per_page\": 10, \"has_more\": true }\n}\n Cursor request
GET /articles/?pagination_type=cursor&items_per_page=10\nGET /articles/?pagination_type=cursor&items_per_page=10&cursor=eyJ2YWx1ZSI6...\n {\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"cursor\",\n \"data\": [\"...\"],\n \"pagination\": { \"next_cursor\": \"eyJ2YWx1ZSI6...\", \"prev_cursor\": null, \"items_per_page\": 10, \"has_more\": true }\n}\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"examples/pagination-search/#search-behaviour","level":2,"title":"Search behaviour","text":"Both endpoints inherit the same searchable_fields declared on ArticleCrud:
Search is case-insensitive and uses a LIKE %query% pattern. Pass a SearchConfig instead of a plain string to control case sensitivity or switch to match_mode=\"all\" (AND across all fields instead of OR).
from fastapi_toolsets.crud import SearchConfig\n\n# Both title AND body must contain \"fastapi\"\nresult = await ArticleCrud.offset_paginate(\n session,\n search=SearchConfig(query=\"fastapi\", case_sensitive=True, match_mode=\"all\"),\n search_fields=[Article.title, Article.body],\n)\n","path":["Examples","Pagination & search"],"tags":[]},{"location":"migration/v2/","level":1,"title":"Migrating to v2.0","text":"This page covers every breaking change introduced in v2.0 and the steps required to update your code.
","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#crud","level":2,"title":"CRUD","text":"","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#schema-is-now-required-in-offset_paginate-and-cursor_paginate","level":3,"title":"schema is now required in offset_paginate() and cursor_paginate()","text":"Calls that omit schema will now raise a TypeError at runtime.
Previously schema was optional; omitting it returned raw SQLAlchemy model instances inside the response. It is now a required keyword argument and the response always contains serialized schema instances.
v1)Now (v2) # schema omitted — returned raw model instances\nresult = await UserCrud.offset_paginate(session=session, page=1)\nresult = await UserCrud.cursor_paginate(session=session, cursor=token)\n result = await UserCrud.offset_paginate(session=session, page=1, schema=UserRead)\nresult = await UserCrud.cursor_paginate(session=session, cursor=token, schema=UserRead)\n","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#as_response-removed-from-create-get-and-update","level":3,"title":"as_response removed from create(), get(), and update()","text":"Passing as_response to these methods will raise a TypeError at runtime.
The as_response=True shorthand is replaced by passing a schema directly. The return value is a Response[schema] when schema is provided, or the raw model instance when it is not.
v1)Now (v2) user = await UserCrud.create(session=session, obj=data, as_response=True)\nuser = await UserCrud.get(session=session, filters=filters, as_response=True)\nuser = await UserCrud.update(session=session, obj=data, filters, as_response=True)\n user = await UserCrud.create(session=session, obj=data, schema=UserRead)\nuser = await UserCrud.get(session=session, filters=filters, schema=UserRead)\nuser = await UserCrud.update(session=session, obj=data, filters, schema=UserRead)\n","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#delete-as_response-renamed-and-return-type-changed","level":3,"title":"delete(): as_response renamed and return type changed","text":"as_response is gone, and the plain (non-response) call no longer returns True.
Two changes were made to delete():
as_response parameter is renamed to return_response.return_response=True, the method now returns None on success instead of True.v1)Now (v2) ok = await UserCrud.delete(session=session, filters=filters)\nif ok: # True on success\n ...\n\nresponse = await UserCrud.delete(session=session, filters=filters, as_response=True)\n await UserCrud.delete(session=session, filters=filters) # returns None\n\nresponse = await UserCrud.delete(session=session, filters=filters, return_response=True)\n","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#paginate-alias-removed","level":3,"title":"paginate() alias removed","text":"Any call to crud.paginate(...) will raise AttributeError at runtime.
The paginate shorthand was an alias for offset_paginate. It has been removed; call offset_paginate directly.
v1)Now (v2) result = await UserCrud.paginate(session=session, page=2, items_per_page=20, schema=UserRead)\n result = await UserCrud.offset_paginate(session=session, page=2, items_per_page=20, schema=UserRead)\n","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#exceptions","level":2,"title":"Exceptions","text":"","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#missing-api_error-raises-typeerror-at-class-definition-time","level":3,"title":"Missing api_error raises TypeError at class definition time","text":"Unfinished or stub exception subclasses that previously compiled fine will now fail on import.
In v1, a subclass without api_error would only fail when the exception was raised. In v2, __init_subclass__ validates this at class definition time.
v1)Now (v2) class MyError(ApiException):\n pass # fine until raised\n class MyError(ApiException):\n pass # TypeError: MyError must define an 'api_error' class attribute.\n For shared base classes that are not meant to be raised directly, use abstract=True:
class BillingError(ApiException, abstract=True):\n \"\"\"Base for all billing-related errors — not raised directly.\"\"\"\n\nclass PaymentRequiredError(BillingError):\n api_error = ApiError(code=402, msg=\"Payment Required\", desc=\"...\", err_code=\"BILLING-402\")\n","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#schemas","level":2,"title":"Schemas","text":"","path":["Migration","Migrating to v2.0"],"tags":[]},{"location":"migration/v2/#pagination-alias-removed","level":3,"title":"Pagination alias removed","text":"Pagination was already deprecated in v1 and is fully removed in v2, you now need to use OffsetPagination or CursorPagination.
Typer-based command-line interface for managing your FastAPI application, with built-in fixture commands integration.
","path":["Modules","CLI"],"tags":[]},{"location":"module/cli/#installation","level":2,"title":"Installation","text":"uvpipuv add \"fastapi-toolsets[cli]\"\n pip install \"fastapi-toolsets[cli]\"\n","path":["Modules","CLI"],"tags":[]},{"location":"module/cli/#overview","level":2,"title":"Overview","text":"The cli module provides a manager entry point built with Typer. It allow custom commands to be added in addition of the fixture commands when a FixtureRegistry and a database context are configured.
Configure the CLI in your pyproject.toml:
[tool.fastapi-toolsets]\ncli = \"myapp.cli:cli\" # Custom Typer app\nfixtures = \"myapp.fixtures:registry\" # FixtureRegistry instance\ndb_context = \"myapp.db:db_context\" # Async context manager for sessions\n All fields are optional. Without configuration, the manager command still works but no command are available.
# Manager commands\nmanager --help\n\n Usage: manager [OPTIONS] COMMAND [ARGS]...\n\n FastAPI utilities CLI.\n\n╭─ Options ────────────────────────────────────────────────────────────────────────╮\n│ --install-completion Install completion for the current shell. │\n│ --show-completion Show completion for the current shell, to copy it │\n│ or customize the installation. │\n│ --help Show this message and exit. │\n╰──────────────────────────────────────────────────────────────────────────────────╯\n╭─ Commands ───────────────────────────────────────────────────────────────────────╮\n│ check-db │\n│ fixtures Manage database fixtures. │\n╰──────────────────────────────────────────────────────────────────────────────────╯\n\n# Fixtures commands\nmanager fixtures --help\n\n Usage: manager fixtures [OPTIONS] COMMAND [ARGS]...\n\n Manage database fixtures.\n\n╭─ Options ────────────────────────────────────────────────────────────────────────╮\n│ --help Show this message and exit. │\n╰──────────────────────────────────────────────────────────────────────────────────╯\n╭─ Commands ───────────────────────────────────────────────────────────────────────╮\n│ list List all registered fixtures. │\n│ load Load fixtures into the database. │\n╰──────────────────────────────────────────────────────────────────────────────────╯\n","path":["Modules","CLI"],"tags":[]},{"location":"module/cli/#custom-cli","level":2,"title":"Custom CLI","text":"You can extend the CLI by providing your own Typer app. The manager entry point will merge your app's commands with the built-in ones:
# myapp/cli.py\nimport typer\n\ncli = typer.Typer()\n\n@cli.command()\ndef hello():\n print(\"Hello from my app!\")\n [tool.fastapi-toolsets]\ncli = \"myapp.cli:cli\"\n API Reference
","path":["Modules","CLI"],"tags":[]},{"location":"module/crud/","level":1,"title":"CRUD","text":"Generic async CRUD operations for SQLAlchemy models with search, pagination, and many-to-many support.
Info
This module has been coded and tested to be compatible with PostgreSQL only.
","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#overview","level":2,"title":"Overview","text":"The crud module provides AsyncCrud, a base class with a full suite of async database operations, and CrudFactory, a convenience function to instantiate it for a given model.
from fastapi_toolsets.crud import CrudFactory\nfrom myapp.models import User\n\nUserCrud = CrudFactory(model=User)\n CrudFactory dynamically creates a class named AsyncUserCrud with User as its model. This is the most concise option for straightforward CRUD with no custom logic.
Added in v2.3.0
from fastapi_toolsets.crud.factory import AsyncCrud\nfrom myapp.models import User\n\nclass UserCrud(AsyncCrud[User]):\n model = User\n searchable_fields = [User.username, User.email]\n default_load_options = [selectinload(User.role)]\n Subclassing AsyncCrud directly is the preferred style when you need to add custom methods or when the configuration is complex enough to benefit from a named class body.
class UserCrud(AsyncCrud[User]):\n model = User\n\n @classmethod\n async def get_active(cls, session: AsyncSession) -> list[User]:\n return await cls.get_multi(session, filters=[User.is_active == True])\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#sharing-a-custom-base-across-multiple-models","level":3,"title":"Sharing a custom base across multiple models","text":"Define a generic base class with the shared methods, then subclass it for each model:
from typing import Generic, TypeVar\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy.orm import DeclarativeBase\nfrom fastapi_toolsets.crud.factory import AsyncCrud\n\nT = TypeVar(\"T\", bound=DeclarativeBase)\n\nclass AuditedCrud(AsyncCrud[T], Generic[T]):\n \"\"\"Base CRUD with custom function\"\"\"\n\n @classmethod\n async def get_active(cls, session: AsyncSession):\n return await cls.get_multi(session, filters=[cls.model.is_active == True])\n\n\nclass UserCrud(AuditedCrud[User]):\n model = User\n searchable_fields = [User.username, User.email]\n You can also use the factory shorthand with the same base by passing base_class:
UserCrud = CrudFactory(User, base_class=AuditedCrud)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#basic-operations","level":2,"title":"Basic operations","text":"get_or_none added in v2.2
# Create\nuser = await UserCrud.create(session=session, obj=UserCreateSchema(username=\"alice\"))\n\n# Get one (raises NotFoundError if not found)\nuser = await UserCrud.get(session=session, filters=[User.id == user_id])\n\n# Get one or None (never raises)\nuser = await UserCrud.get_or_none(session=session, filters=[User.id == user_id])\n\n# Get first or None\nuser = await UserCrud.first(session=session, filters=[User.email == email])\n\n# Get multiple\nusers = await UserCrud.get_multi(session=session, filters=[User.is_active == True])\n\n# Update\nuser = await UserCrud.update(session=session, obj=UserUpdateSchema(username=\"bob\"), filters=[User.id == user_id])\n\n# Delete\nawait UserCrud.delete(session=session, filters=[User.id == user_id])\n\n# Count / exists\ncount = await UserCrud.count(session=session, filters=[User.is_active == True])\nexists = await UserCrud.exists(session=session, filters=[User.email == email])\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#fetching-a-single-record","level":2,"title":"Fetching a single record","text":"Three methods fetch a single record — choose based on how you want to handle the \"not found\" case and whether you need strict uniqueness:
Method Not found Multiple resultsget raises NotFoundError raises MultipleResultsFound get_or_none returns None raises MultipleResultsFound first returns None returns the first match silently Use get when the record must exist (e.g. a detail endpoint that should return 404):
user = await UserCrud.get(session=session, filters=[User.id == user_id])\n Use get_or_none when the record may not exist but you still want strict uniqueness enforcement:
user = await UserCrud.get_or_none(session=session, filters=[User.email == email])\nif user is None:\n ... # handle missing case without catching an exception\n Use first when you only care about any one match and don't need uniqueness:
user = await UserCrud.first(session=session, filters=[User.is_active == True])\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#pagination","level":2,"title":"Pagination","text":"Added in v1.1 (only offset_pagination via paginate if <v1.1)
Three pagination methods are available. All return a typed response whose pagination_type field tells clients which strategy was used.
offset_paginate cursor_paginate paginate Return type OffsetPaginatedResponse CursorPaginatedResponse either, based on pagination_type param Total count Yes No / Jump to arbitrary page Yes No / Performance on deep pages Degrades Constant / Stable under concurrent inserts No Yes / Use case Admin panels, numbered pagination Feeds, APIs, infinite scroll single endpoint, both strategies","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#offset-pagination","level":3,"title":"Offset pagination","text":"@router.get(\"\")\nasync def get_users(\n session: SessionDep,\n items_per_page: int = 50,\n page: int = 1,\n) -> OffsetPaginatedResponse[UserRead]:\n return await UserCrud.offset_paginate(\n session=session,\n items_per_page=items_per_page,\n page=page,\n schema=UserRead,\n )\n The offset_paginate method returns an OffsetPaginatedResponse:
{\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"offset\",\n \"data\": [\"...\"],\n \"pagination\": {\n \"total_count\": 100,\n \"pages\": 5,\n \"page\": 1,\n \"items_per_page\": 20,\n \"has_more\": true\n }\n}\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#skipping-the-count-query","level":4,"title":"Skipping the COUNT query","text":"Added in v2.4.1
By default offset_paginate runs two queries: one for the page items and one COUNT(*) for total_count. On large tables the COUNT can be expensive. Pass include_total=False to skip it:
result = await UserCrud.offset_paginate(\n session=session,\n page=page,\n items_per_page=items_per_page,\n include_total=False,\n schema=UserRead,\n)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#pagination-params-dependency","level":4,"title":"Pagination params dependency","text":"Added in v2.4.1
Use offset_params() to generate a FastAPI dependency that injects page and items_per_page from query parameters with configurable defaults and a max_page_size cap:
from typing import Annotated\nfrom fastapi import Depends\n\n@router.get(\"\")\nasync def list_users(\n session: SessionDep,\n params: Annotated[dict, Depends(UserCrud.offset_params(default_page_size=20, max_page_size=100))],\n) -> OffsetPaginatedResponse[UserRead]:\n return await UserCrud.offset_paginate(session=session, **params, schema=UserRead)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#cursor-pagination","level":3,"title":"Cursor pagination","text":"@router.get(\"\")\nasync def list_users(\n session: SessionDep,\n cursor: str | None = None,\n items_per_page: int = 20,\n) -> CursorPaginatedResponse[UserRead]:\n return await UserCrud.cursor_paginate(\n session=session,\n cursor=cursor,\n items_per_page=items_per_page,\n schema=UserRead,\n )\n The cursor_paginate method returns a CursorPaginatedResponse:
{\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"cursor\",\n \"data\": [\"...\"],\n \"pagination\": {\n \"next_cursor\": \"eyJ2YWx1ZSI6ICIzZjQ3YWM2OS0uLi4ifQ==\",\n \"prev_cursor\": null,\n \"items_per_page\": 20,\n \"has_more\": true\n }\n}\n Pass next_cursor as the cursor query parameter on the next request to advance to the next page. prev_cursor is set on pages 2+ and points back to the first item of the current page. Both are null when there is no adjacent page.
The cursor column is set once on CrudFactory via the cursor_column parameter. It must be monotonically ordered for stable results:
Warning
Random UUID v4 PKs are not suitable as cursor columns because their ordering is non-deterministic.
Note
cursor_column is required. Calling cursor_paginate on a CRUD class that has no cursor_column configured raises a ValueError.
The cursor value is URL-safe base64-encoded (no padding) when returned to the client and decoded back to the correct Python type on the next request. The following SQLAlchemy column types are supported:
SQLAlchemy type Python typeInteger, BigInteger, SmallInteger int Uuid uuid.UUID DateTime datetime.datetime Date datetime.date Float, Numeric decimal.Decimal # Paginate by the primary key\nPostCrud = CrudFactory(model=Post, cursor_column=Post.id)\n\n# Paginate by a timestamp column instead\nPostCrud = CrudFactory(model=Post, cursor_column=Post.created_at)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#pagination-params-dependency_1","level":4,"title":"Pagination params dependency","text":"Added in v2.4.1
Use cursor_params() to inject cursor and items_per_page from query parameters with a max_page_size cap:
from typing import Annotated\nfrom fastapi import Depends\n\n@router.get(\"\")\nasync def list_users(\n session: SessionDep,\n params: Annotated[dict, Depends(UserCrud.cursor_params(default_page_size=20, max_page_size=100))],\n) -> CursorPaginatedResponse[UserRead]:\n return await UserCrud.cursor_paginate(session=session, **params, schema=UserRead)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#unified-endpoint-both-strategies","level":3,"title":"Unified endpoint (both strategies)","text":"Added in v2.3.0
paginate() dispatches to offset_paginate or cursor_paginate based on a pagination_type query parameter, letting you expose one endpoint that supports both strategies. The pagination_type field in the response tells clients which strategy was used, enabling frontend discriminated-union typing.
from fastapi_toolsets.crud import PaginationType\nfrom fastapi_toolsets.schemas import PaginatedResponse\n\n@router.get(\"\")\nasync def list_users(\n session: SessionDep,\n pagination_type: PaginationType = PaginationType.OFFSET,\n page: int = Query(1, ge=1, description=\"Current page (offset only)\"),\n cursor: str | None = Query(None, description=\"Cursor token (cursor only)\"),\n items_per_page: int = Query(20, ge=1, le=100),\n) -> PaginatedResponse[UserRead]:\n return await UserCrud.paginate(\n session,\n pagination_type=pagination_type,\n page=page,\n cursor=cursor,\n items_per_page=items_per_page,\n schema=UserRead,\n )\n GET /users?pagination_type=offset&page=2&items_per_page=10\nGET /users?pagination_type=cursor&cursor=eyJ2YWx1ZSI6...&items_per_page=10\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#pagination-params-dependency_2","level":4,"title":"Pagination params dependency","text":"Added in v2.4.1
Use paginate_params() to inject all parameters at once with configurable defaults and a max_page_size cap:
from typing import Annotated\nfrom fastapi import Depends\nfrom fastapi_toolsets.schemas import PaginatedResponse\n\n@router.get(\"\")\nasync def list_users(\n session: SessionDep,\n params: Annotated[dict, Depends(UserCrud.paginate_params(default_page_size=20, max_page_size=100))],\n) -> PaginatedResponse[UserRead]:\n return await UserCrud.paginate(session, **params, schema=UserRead)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#search","level":2,"title":"Search","text":"Two search strategies are available, both compatible with offset_paginate and cursor_paginate.
You can use both search strategies in the same endpoint!
","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#full-text-search","level":3,"title":"Full-text search","text":"Added in v2.2.1
The model's primary key is always included in searchable_fields automatically, so searching by ID works out of the box without any configuration. When no searchable_fields are declared, only the primary key is searched.
Declare searchable_fields on the CRUD class. Relationship traversal is supported via tuples:
PostCrud = CrudFactory(\n model=Post,\n searchable_fields=[\n Post.title,\n Post.content,\n (Post.author, User.username), # search across relationship\n ],\n)\n You can override searchable_fields per call with search_fields:
result = await UserCrud.offset_paginate(\n session=session,\n search_fields=[User.country],\n)\n This allows searching with both offset_paginate and cursor_paginate:
@router.get(\"\")\nasync def get_users(\n session: SessionDep,\n items_per_page: int = 50,\n page: int = 1,\n search: str | None = None,\n) -> OffsetPaginatedResponse[UserRead]:\n return await UserCrud.offset_paginate(\n session=session,\n items_per_page=items_per_page,\n page=page,\n search=search,\n schema=UserRead,\n )\n @router.get(\"\")\nasync def get_users(\n session: SessionDep,\n cursor: str | None = None,\n items_per_page: int = 50,\n search: str | None = None,\n) -> CursorPaginatedResponse[UserRead]:\n return await UserCrud.cursor_paginate(\n session=session,\n items_per_page=items_per_page,\n cursor=cursor,\n search=search,\n schema=UserRead,\n )\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#faceted-search","level":3,"title":"Faceted search","text":"Added in v1.2
Declare facet_fields on the CRUD class to return distinct column values alongside paginated results. This is useful for populating filter dropdowns or building faceted search UIs.
Facet fields use the same syntax as searchable_fields — direct columns or relationship tuples:
UserCrud = CrudFactory(\n model=User,\n facet_fields=[\n User.status,\n User.country,\n (User.role, Role.name), # value from a related model\n ],\n)\n You can override facet_fields per call:
result = await UserCrud.offset_paginate(\n session=session,\n facet_fields=[User.country],\n)\n The distinct values are returned in the filter_attributes field of PaginatedResponse:
{\n \"status\": \"SUCCESS\",\n \"data\": [\"...\"],\n \"pagination\": { \"...\" },\n \"filter_attributes\": {\n \"status\": [\"active\", \"inactive\"],\n \"country\": [\"DE\", \"FR\", \"US\"],\n \"name\": [\"admin\", \"editor\", \"viewer\"]\n }\n}\n Use filter_by to pass the client's chosen filter values directly — no need to build SQLAlchemy conditions by hand. Any unknown key raises InvalidFacetFilterError.
The keys in filter_by are the same keys the client received in filter_attributes.
Keys are normally the terminal column.key (e.g. \"name\" for Role.name). When two facet fields share the same column key (e.g. (Build.project, Project.name) and (Build.os, Os.name)), the relationship name is prepended automatically: \"project__name\" and \"os__name\".
filter_by and filters can be combined — both are applied with AND logic.
Use filter_params() to generate a dict with the facet filter values from the query parameters:
from typing import Annotated\n\nfrom fastapi import Depends\n\nUserCrud = CrudFactory(\n model=User,\n facet_fields=[User.status, User.country, (User.role, Role.name)],\n)\n\n@router.get(\"\", response_model_exclude_none=True)\nasync def list_users(\n session: SessionDep,\n page: int = 1,\n filter_by: Annotated[dict[str, list[str]], Depends(UserCrud.filter_params())],\n) -> OffsetPaginatedResponse[UserRead]:\n return await UserCrud.offset_paginate(\n session=session,\n page=page,\n filter_by=filter_by,\n schema=UserRead,\n )\n Both single-value and multi-value query parameters work:
GET /users?status=active → filter_by={\"status\": [\"active\"]}\nGET /users?status=active&country=FR → filter_by={\"status\": [\"active\"], \"country\": [\"FR\"]}\nGET /users?role=admin&role=editor → filter_by={\"role\": [\"admin\", \"editor\"]} (IN clause)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#sorting","level":2,"title":"Sorting","text":"Added in v1.3
Declare order_fields on the CRUD class to expose client-driven column ordering via order_by and order query parameters.
UserCrud = CrudFactory(\n model=User,\n order_fields=[\n User.name,\n User.created_at,\n ],\n)\n Call order_params() to generate a FastAPI dependency that maps the query parameters to an OrderByClause expression:
from typing import Annotated\n\nfrom fastapi import Depends\nfrom fastapi_toolsets.crud import OrderByClause\n\n@router.get(\"\")\nasync def list_users(\n session: SessionDep,\n order_by: Annotated[OrderByClause | None, Depends(UserCrud.order_params())],\n) -> OffsetPaginatedResponse[UserRead]:\n return await UserCrud.offset_paginate(session=session, order_by=order_by, schema=UserRead)\n The dependency adds two query parameters to the endpoint:
Parameter Typeorder_by str | null order asc or desc GET /users?order_by=name&order=asc → ORDER BY users.name ASC\nGET /users?order_by=name&order=desc → ORDER BY users.name DESC\n An unknown order_by value raises InvalidOrderFieldError (HTTP 422).
You can also pass order_fields directly to order_params() to override the class-level defaults without modifying them:
UserOrderParams = UserCrud.order_params(order_fields=[User.name])\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#relationship-loading","level":2,"title":"Relationship loading","text":"Added in v1.1
By default, SQLAlchemy relationships are not loaded unless explicitly requested. Instead of using lazy=\"selectin\" on model definitions (which is implicit and applies globally), define a default_load_options on the CRUD class to control loading strategy explicitly.
Warning
Avoid using lazy=\"selectin\" on model relationships. It fires silently on every query, cannot be disabled per-call, and can cause unexpected cascading loads through deep relationship chains. Use default_load_options instead.
from sqlalchemy.orm import selectinload\n\nArticleCrud = CrudFactory(\n model=Article,\n default_load_options=[\n selectinload(Article.category),\n selectinload(Article.tags),\n ],\n)\n default_load_options applies automatically to all read operations (get, first, get_multi, offset_paginate, cursor_paginate). When load_options is passed at call-site, it fully replaces default_load_options for that query — giving you precise per-call control:
# Only loads category, tags are not loaded\narticle = await ArticleCrud.get(\n session=session,\n filters=[Article.id == article_id],\n load_options=[selectinload(Article.category)],\n)\n\n# Loads nothing — useful for write-then-refresh flows or lightweight checks\narticles = await ArticleCrud.get_multi(session=session, load_options=[])\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#many-to-many-relationships","level":2,"title":"Many-to-many relationships","text":"Use m2m_fields to map schema fields containing lists of IDs to SQLAlchemy relationships. The CRUD class resolves and validates all IDs before persisting:
PostCrud = CrudFactory(\n model=Post,\n m2m_fields={\"tag_ids\": Post.tags},\n)\n\npost = await PostCrud.create(session=session, obj=PostCreateSchema(title=\"Hello\", tag_ids=[1, 2, 3]))\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#upsert","level":2,"title":"Upsert","text":"Atomic INSERT ... ON CONFLICT DO UPDATE using PostgreSQL:
await UserCrud.upsert(\n session=session,\n obj=UserCreateSchema(email=\"alice@example.com\", username=\"alice\"),\n index_elements=[User.email],\n set_={\"username\"},\n)\n","path":["Modules","CRUD"],"tags":[]},{"location":"module/crud/#response-serialization","level":2,"title":"Response serialization","text":"Added in v1.1
Pass a Pydantic schema class to create, get, update, or offset_paginate to serialize the result directly into that schema and wrap it in a Response[schema] or PaginatedResponse[schema]:
class UserRead(PydanticBase):\n id: UUID\n username: str\n\n@router.get(\n \"/{uuid}\",\n responses=generate_error_responses(NotFoundError),\n)\nasync def get_user(session: SessionDep, uuid: UUID) -> Response[UserRead]:\n return await crud.UserCrud.get(\n session=session,\n filters=[User.id == uuid],\n schema=UserRead,\n )\n\n@router.get(\"\")\nasync def list_users(session: SessionDep, page: int = 1) -> OffsetPaginatedResponse[UserRead]:\n return await crud.UserCrud.offset_paginate(\n session=session,\n page=page,\n schema=UserRead,\n )\n The schema must have from_attributes=True (or inherit from PydanticBase) so it can be built from SQLAlchemy model instances.
API Reference
","path":["Modules","CRUD"],"tags":[]},{"location":"module/db/","level":1,"title":"DB","text":"SQLAlchemy async session management with transactions, table locking, and row-change polling.
Info
This module has been coded and tested to be compatible with PostgreSQL only.
","path":["Modules","DB"],"tags":[]},{"location":"module/db/#overview","level":2,"title":"Overview","text":"The db module provides helpers to create FastAPI dependencies and context managers for AsyncSession, along with utilities for nested transactions, table lock and polling for row changes.
Use create_db_dependency to create a FastAPI dependency that yields a session and auto-commits on success:
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker\nfrom fastapi_toolsets.db import create_db_dependency\n\nengine = create_async_engine(url=\"postgresql+asyncpg://...\", future=True)\nsession_maker = async_sessionmaker(bind=engine, expire_on_commit=False)\n\nget_db = create_db_dependency(session_maker=session_maker)\n\n@router.get(\"/users\")\nasync def list_users(session: AsyncSession = Depends(get_db)):\n ...\n","path":["Modules","DB"],"tags":[]},{"location":"module/db/#session-context-manager","level":2,"title":"Session context manager","text":"Use create_db_context for sessions outside request handlers (e.g. background tasks, CLI commands):
from fastapi_toolsets.db import create_db_context\n\ndb_context = create_db_context(session_maker=session_maker)\n\nasync def seed():\n async with db_context() as session:\n ...\n","path":["Modules","DB"],"tags":[]},{"location":"module/db/#nested-transactions","level":2,"title":"Nested transactions","text":"get_transaction handles savepoints automatically, allowing safe nesting:
from fastapi_toolsets.db import get_transaction\n\nasync def create_user_with_role(session=session):\n async with get_transaction(session=session):\n ...\n async with get_transaction(session=session): # uses savepoint\n ...\n","path":["Modules","DB"],"tags":[]},{"location":"module/db/#table-locking","level":2,"title":"Table locking","text":"lock_tables acquires PostgreSQL table-level locks before executing critical sections:
from fastapi_toolsets.db import lock_tables\n\nasync with lock_tables(session=session, tables=[User], mode=\"EXCLUSIVE\"):\n # No other transaction can modify User until this block exits\n ...\n Available lock modes are defined in LockMode: ACCESS_SHARE, ROW_SHARE, ROW_EXCLUSIVE, SHARE_UPDATE_EXCLUSIVE, SHARE, SHARE_ROW_EXCLUSIVE, EXCLUSIVE, ACCESS_EXCLUSIVE.
wait_for_row_change polls a row until a specific column changes value, useful for waiting on async side effects:
from fastapi_toolsets.db import wait_for_row_change\n\n# Wait up to 30s for order.status to change\nawait wait_for_row_change(\n session=session,\n model=Order,\n pk_value=order_id,\n columns=[Order.status],\n interval=1.0,\n timeout=30.0,\n)\n","path":["Modules","DB"],"tags":[]},{"location":"module/db/#creating-a-database","level":2,"title":"Creating a database","text":"Added in v2.1
create_database creates a database at a given URL. It connects to server_url and issues a CREATE DATABASE statement:
from fastapi_toolsets.db import create_database\n\nSERVER_URL = \"postgresql+asyncpg://postgres:postgres@localhost/postgres\"\n\nawait create_database(db_name=\"myapp_test\", server_url=SERVER_URL)\n For test isolation with automatic cleanup, use create_worker_database from the pytest module instead — it handles drop-before, create, and drop-after automatically.
Added in v2.1
cleanup_tables truncates all tables:
from fastapi_toolsets.db import cleanup_tables\n\n@pytest.fixture(autouse=True)\nasync def clean(db_session):\n yield\n await cleanup_tables(session=db_session, base=Base)\n API Reference
","path":["Modules","DB"],"tags":[]},{"location":"module/dependencies/","level":1,"title":"Dependencies","text":"FastAPI dependency factories for automatic model resolution from path and body parameters.
","path":["Modules","Dependencies"],"tags":[]},{"location":"module/dependencies/#overview","level":2,"title":"Overview","text":"The dependencies module provides two factory functions that create FastAPI dependencies to fetch a model instance from the database automatically — either from a path parameter or from a request body field — and inject it directly into your route handler.
PathDependency","text":"PathDependency resolves a model from a URL path parameter and injects it into the route handler. Raises NotFoundError automatically if the record does not exist.
from fastapi_toolsets.dependencies import PathDependency\n\n# Plain callable\nUserDep = PathDependency(model=User, field=User.id, session_dep=get_db)\n\n# Annotated\nSessionDep = Annotated[AsyncSession, Depends(get_db)]\nUserDep = PathDependency(model=User, field=User.id, session_dep=SessionDep)\n\n@router.get(\"/users/{user_id}\")\nasync def get_user(user: User = UserDep):\n return user\n By default the parameter name is inferred from the field (user_id for User.id). You can override it:
UserDep = PathDependency(model=User, field=User.id, session_dep=get_db, param_name=\"id\")\n\n@router.get(\"/users/{id}\")\nasync def get_user(user: User = UserDep):\n return user\n","path":["Modules","Dependencies"],"tags":[]},{"location":"module/dependencies/#bodydependency","level":2,"title":"BodyDependency","text":"BodyDependency resolves a model from a field in the request body. Useful when a body contains a foreign key and you want the full object injected:
from fastapi_toolsets.dependencies import BodyDependency\n\n# Plain callable\nRoleDep = BodyDependency(model=Role, field=Role.id, session_dep=get_db, body_field=\"role_id\")\n\n# Annotated\nSessionDep = Annotated[AsyncSession, Depends(get_db)]\nRoleDep = BodyDependency(model=Role, field=Role.id, session_dep=SessionDep, body_field=\"role_id\")\n\n\n@router.post(\"/users\")\nasync def create_user(body: UserCreateSchema, role: Role = RoleDep):\n user = User(username=body.username, role=role)\n ...\n API Reference
","path":["Modules","Dependencies"],"tags":[]},{"location":"module/exceptions/","level":1,"title":"Exceptions","text":"Structured API exceptions with consistent error responses and automatic OpenAPI documentation.
","path":["Modules","Exceptions"],"tags":[]},{"location":"module/exceptions/#overview","level":2,"title":"Overview","text":"The exceptions module provides a set of pre-built HTTP exceptions and a FastAPI exception handler that formats all errors — including validation errors — into a uniform ErrorResponse.
Register the exception handlers on your FastAPI app at startup:
from fastapi import FastAPI\nfrom fastapi_toolsets.exceptions import init_exceptions_handlers\n\napp = FastAPI()\ninit_exceptions_handlers(app=app)\n This registers handlers for:
ApiException — all custom exceptions belowHTTPException — Starlette/FastAPI HTTP errorsRequestValidationError — Pydantic request validation (422)ResponseValidationError — Pydantic response validation (422)Exception — unhandled errors (500)It also patches app.openapi() to replace the default Pydantic 422 schema with a structured example matching the ErrorResponse format.
UnauthorizedError 401 Unauthorized ForbiddenError 403 Forbidden NotFoundError 404 Not Found ConflictError 409 Conflict NoSearchableFieldsError 400 No Searchable Fields InvalidFacetFilterError 400 Invalid Facet Filter InvalidOrderFieldError 422 Invalid Order Field","path":["Modules","Exceptions"],"tags":[]},{"location":"module/exceptions/#per-instance-overrides","level":3,"title":"Per-instance overrides","text":"All built-in exceptions accept optional keyword arguments to customise the response for a specific raise site without changing the class defaults:
Argument Effectdetail Overrides both str(exc) (log output) and the message field in the response body desc Overrides the description field data Overrides the data field raise NotFoundError(detail=\"User 42 not found\", desc=\"No user with that ID exists in the database.\")\n","path":["Modules","Exceptions"],"tags":[]},{"location":"module/exceptions/#custom-exceptions","level":2,"title":"Custom exceptions","text":"Subclass ApiException and define an api_error class variable:
from fastapi_toolsets.exceptions import ApiException\nfrom fastapi_toolsets.schemas import ApiError\n\nclass PaymentRequiredError(ApiException):\n api_error = ApiError(\n code=402,\n msg=\"Payment Required\",\n desc=\"Your subscription has expired.\",\n err_code=\"BILLING-402\",\n )\n Warning
Subclasses that do not define api_error raise a TypeError at class creation time, not at raise time.
__init__","text":"Override __init__ to compute detail, desc, or data dynamically, then delegate to super().__init__():
class OrderValidationError(ApiException):\n api_error = ApiError(\n code=422,\n msg=\"Order Validation Failed\",\n desc=\"One or more order fields are invalid.\",\n err_code=\"ORDER-422\",\n )\n\n def __init__(self, *field_errors: str) -> None:\n super().__init__(\n f\"{len(field_errors)} validation error(s)\",\n desc=\", \".join(field_errors),\n data={\"errors\": [{\"message\": e} for e in field_errors]},\n )\n","path":["Modules","Exceptions"],"tags":[]},{"location":"module/exceptions/#intermediate-base-classes","level":3,"title":"Intermediate base classes","text":"Use abstract=True when creating a shared base that is not meant to be raised directly:
class BillingError(ApiException, abstract=True):\n \"\"\"Base for all billing-related errors.\"\"\"\n\nclass PaymentRequiredError(BillingError):\n api_error = ApiError(code=402, msg=\"Payment Required\", desc=\"...\", err_code=\"BILLING-402\")\n\nclass SubscriptionExpiredError(BillingError):\n api_error = ApiError(code=402, msg=\"Subscription Expired\", desc=\"...\", err_code=\"BILLING-402-EXP\")\n","path":["Modules","Exceptions"],"tags":[]},{"location":"module/exceptions/#openapi-response-documentation","level":2,"title":"OpenAPI response documentation","text":"Use generate_error_responses to add error schemas to your endpoint's OpenAPI spec:
from fastapi_toolsets.exceptions import generate_error_responses, NotFoundError, ForbiddenError\n\n@router.get(\n \"/users/{id}\",\n responses=generate_error_responses(NotFoundError, ForbiddenError),\n)\nasync def get_user(...): ...\n Multiple exceptions sharing the same HTTP status code are grouped under one entry, each appearing as a named example keyed by its err_code. This keeps the OpenAPI UI readable when several error variants map to the same status.
API Reference
","path":["Modules","Exceptions"],"tags":[]},{"location":"module/fixtures/","level":1,"title":"Fixtures","text":"Dependency-aware database seeding with context-based loading strategies.
","path":["Modules","Fixtures"],"tags":[]},{"location":"module/fixtures/#overview","level":2,"title":"Overview","text":"The fixtures module lets you define named fixtures with dependencies between them, then load them into the database in the correct order. Fixtures can be scoped to contexts (e.g. base data, testing data) so that only the relevant ones are loaded for each environment.
from fastapi_toolsets.fixtures import FixtureRegistry, Context\n\nfixtures = FixtureRegistry()\n\n@fixtures.register\ndef roles():\n return [\n Role(id=1, name=\"admin\"),\n Role(id=2, name=\"user\"),\n ]\n\n@fixtures.register(depends_on=[\"roles\"], contexts=[Context.TESTING])\ndef test_users():\n return [\n User(id=1, username=\"alice\", role_id=1),\n User(id=2, username=\"bob\", role_id=2),\n ]\n Dependencies declared via depends_on are resolved topologically — roles will always be loaded before test_users.
By context with load_fixtures_by_context:
from fastapi_toolsets.fixtures import load_fixtures_by_context\n\nasync with db_context() as session:\n await load_fixtures_by_context(session=session, registry=fixtures, context=Context.TESTING)\n Directly with load_fixtures:
from fastapi_toolsets.fixtures import load_fixtures\n\nasync with db_context() as session:\n await load_fixtures(session=session, registry=fixtures)\n","path":["Modules","Fixtures"],"tags":[]},{"location":"module/fixtures/#contexts","level":2,"title":"Contexts","text":"Context is an enum with predefined values:
Context.BASE Core data required in all environments Context.TESTING Data only loaded during tests Context.PRODUCTION Data only loaded in production A fixture with no contexts defined takes Context.BASE by default.
LoadStrategy controls how the fixture loader handles rows that already exist:
LoadStrategy.INSERT Insert only, fail on duplicates LoadStrategy.UPSERT Insert or update on conflict LoadStrategy.SKIP Skip rows that already exist","path":["Modules","Fixtures"],"tags":[]},{"location":"module/fixtures/#merging-registries","level":2,"title":"Merging registries","text":"Split fixtures definitions across modules and merge them:
from myapp.fixtures.dev import dev_fixtures\nfrom myapp.fixtures.prod import prod_fixtures\n\nfixtures = fixturesRegistry()\nfixtures.include_registry(registry=dev_fixtures)\nfixtures.include_registry(registry=prod_fixtures)\n\n## Pytest integration\n\nUse [`register_fixtures`](../reference/pytest.md#fastapi_toolsets.pytest.plugin.register_fixtures) to expose each fixture in your registry as an injectable pytest fixture named `fixture_{name}` by default:\n\n```python\n# conftest.py\nimport pytest\nfrom fastapi_toolsets.pytest import create_db_session, register_fixtures\nfrom app.fixtures import registry\nfrom app.models import Base\n\nDATABASE_URL = \"postgresql+asyncpg://user:pass@localhost/test_db\"\n\n@pytest.fixture\nasync def db_session():\n async with create_db_session(database_url=DATABASE_URL, base=Base, cleanup=True) as session:\n yield session\n\nregister_fixtures(registry=registry, namespace=globals())\n # test_users.py\nasync def test_user_can_login(fixture_users: list[User], fixture_roles: list[Role]):\n ...\n The load order is resolved automatically from the depends_on declarations in your registry. Each generated fixture receives db_session as a dependency and returns the list of loaded model instances.
Fixtures can be triggered from the CLI. See the CLI module for setup instructions.
API Reference
","path":["Modules","Fixtures"],"tags":[]},{"location":"module/logger/","level":1,"title":"Logger","text":"Lightweight logging utilities with consistent formatting and uvicorn integration.
","path":["Modules","Logger"],"tags":[]},{"location":"module/logger/#overview","level":2,"title":"Overview","text":"The logger module provides two helpers: one to configure the root logger (and uvicorn loggers) at startup, and one to retrieve a named logger anywhere in your codebase.
Call configure_logging once at application startup:
from fastapi_toolsets.logger import configure_logging\n\nconfigure_logging(level=\"INFO\")\n This sets up a stdout handler with a consistent format and also configures uvicorn's access and error loggers so all log output shares the same style.
","path":["Modules","Logger"],"tags":[]},{"location":"module/logger/#getting-a-logger","level":2,"title":"Getting a logger","text":"from fastapi_toolsets.logger import get_logger\n\nlogger = get_logger(name=__name__)\nlogger.info(\"User created\")\n When called without arguments, get_logger auto-detects the caller's module name via frame inspection:
# Equivalent to get_logger(name=__name__)\nlogger = get_logger()\n API Reference
","path":["Modules","Logger"],"tags":[]},{"location":"module/metrics/","level":1,"title":"Metrics","text":"Prometheus metrics integration with a decorator-based registry and multi-process support.
","path":["Modules","Metrics"],"tags":[]},{"location":"module/metrics/#installation","level":2,"title":"Installation","text":"uvpipuv add \"fastapi-toolsets[metrics]\"\n pip install \"fastapi-toolsets[metrics]\"\n","path":["Modules","Metrics"],"tags":[]},{"location":"module/metrics/#overview","level":2,"title":"Overview","text":"The metrics module provides a MetricsRegistry to declare Prometheus metrics with decorators, and an init_metrics function to mount a /metrics endpoint on your FastAPI app.
from fastapi import FastAPI\nfrom fastapi_toolsets.metrics import MetricsRegistry, init_metrics\n\napp = FastAPI()\nmetrics = MetricsRegistry()\n\ninit_metrics(app=app, registry=metrics)\n This mounts the /metrics endpoint that Prometheus can scrape.
Providers are called once at startup by init_metrics. The return value (the Prometheus metric object) is stored in the registry and can be retrieved later with registry.get(name).
Use providers when you want deferred initialization: the Prometheus metric is not registered with the global CollectorRegistry until init_metrics runs, not at import time. This is particularly useful for testing — importing the module in a test suite without calling init_metrics leaves no metrics registered, avoiding cross-test pollution.
It is also useful when metrics are defined across multiple modules and merged with include_registry: any code that needs a metric can call metrics.get() on the shared registry instead of importing the metric directly from its origin module.
If neither of these applies to you, declaring metrics at module level (e.g. HTTP_REQUESTS = Counter(...)) is simpler and equally valid.
from prometheus_client import Counter, Histogram\n\n@metrics.register\ndef http_requests():\n return Counter(\"http_requests_total\", \"Total HTTP requests\", [\"method\", \"status\"])\n\n@metrics.register\ndef request_duration():\n return Histogram(\"request_duration_seconds\", \"Request duration\")\n To use a provider's metric elsewhere (e.g. in a middleware), call metrics.get() inside the handler — not at module level, as providers are only initialized when init_metrics runs:
async def metrics_middleware(request: Request, call_next):\n response = await call_next(request)\n metrics.get(\"http_requests\").labels(\n method=request.method, status=response.status_code\n ).inc()\n return response\n","path":["Modules","Metrics"],"tags":[]},{"location":"module/metrics/#collectors","level":3,"title":"Collectors","text":"Collectors are called on every scrape. Use them for metrics that reflect current state (e.g. gauges).
Declare the metric at module level
Do not instantiate the Prometheus metric inside the collector function. Doing so recreates it on every scrape, raising ValueError: Duplicated timeseries in CollectorRegistry. Declare it once at module level instead:
from prometheus_client import Gauge\n\n_queue_depth = Gauge(\"queue_depth\", \"Current queue depth\")\n\n@metrics.register(collect=True)\ndef collect_queue_depth():\n _queue_depth.set(get_current_queue_depth())\n","path":["Modules","Metrics"],"tags":[]},{"location":"module/metrics/#merging-registries","level":2,"title":"Merging registries","text":"Split metrics definitions across modules and merge them:
from myapp.metrics.http import http_metrics\nfrom myapp.metrics.db import db_metrics\n\nmetrics = MetricsRegistry()\nmetrics.include_registry(registry=http_metrics)\nmetrics.include_registry(registry=db_metrics)\n","path":["Modules","Metrics"],"tags":[]},{"location":"module/metrics/#multi-process-mode","level":2,"title":"Multi-process mode","text":"Multi-process support is enabled automatically when the PROMETHEUS_MULTIPROC_DIR environment variable is set. No code changes are required.
Environment variable name
The correct variable is PROMETHEUS_MULTIPROC_DIR (not PROMETHEUS_MULTIPROCESS_DIR).
API Reference
","path":["Modules","Metrics"],"tags":[]},{"location":"module/models/","level":1,"title":"Models","text":"Added in v2.0
Reusable SQLAlchemy 2.0 mixins for common column patterns, designed to be composed freely on any DeclarativeBase model.
The models module provides mixins that each add a single, well-defined column behaviour. They work with standard SQLAlchemy 2.0 declarative syntax and are fully compatible with AsyncSession.
from fastapi_toolsets.models import UUIDMixin, TimestampMixin\n\nclass Article(Base, UUIDMixin, TimestampMixin):\n __tablename__ = \"articles\"\n\n title: Mapped[str]\n content: Mapped[str]\n All timestamp columns are timezone-aware (TIMESTAMPTZ). All defaults are server-side (clock_timestamp()), so they are also applied when inserting rows via raw SQL outside the ORM.
UUIDMixin","text":"Adds a id: UUID primary key generated server-side by PostgreSQL using gen_random_uuid(). The value is retrieved via RETURNING after insert, so it is available on the Python object immediately after flush().
Requires PostgreSQL 13+
from fastapi_toolsets.models import UUIDMixin\n\nclass User(Base, UUIDMixin):\n __tablename__ = \"users\"\n\n username: Mapped[str]\n\n# id is None before flush\nuser = User(username=\"alice\")\nsession.add(user)\nawait session.flush()\nprint(user.id) # UUID('...')\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#uuidv7mixin","level":3,"title":"UUIDv7Mixin","text":"Added in v2.3
Adds a id: UUID primary key generated server-side by PostgreSQL using uuidv7(). It's a time-ordered UUID format that encodes a millisecond-precision timestamp in the most significant bits, making it naturally sortable and index-friendly.
Requires PostgreSQL 18+
from fastapi_toolsets.models import UUIDv7Mixin\n\nclass Event(Base, UUIDv7Mixin):\n __tablename__ = \"events\"\n\n name: Mapped[str]\n\n# id is None before flush\nevent = Event(name=\"user.signup\")\nsession.add(event)\nawait session.flush()\nprint(event.id) # UUID('019...')\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#createdatmixin","level":3,"title":"CreatedAtMixin","text":"Adds a created_at: datetime column set to clock_timestamp() on insert. The column has no onupdate hook — it is intentionally immutable after the row is created.
from fastapi_toolsets.models import UUIDMixin, CreatedAtMixin\n\nclass Order(Base, UUIDMixin, CreatedAtMixin):\n __tablename__ = \"orders\"\n\n total: Mapped[float]\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#updatedatmixin","level":3,"title":"UpdatedAtMixin","text":"Adds an updated_at: datetime column set to clock_timestamp() on insert and automatically updated to clock_timestamp() on every ORM-level update (via SQLAlchemy's onupdate hook).
from fastapi_toolsets.models import UUIDMixin, UpdatedAtMixin\n\nclass Post(Base, UUIDMixin, UpdatedAtMixin):\n __tablename__ = \"posts\"\n\n title: Mapped[str]\n\npost = Post(title=\"Hello\")\nawait session.flush()\nawait session.refresh(post)\n\npost.title = \"Hello World\"\nawait session.flush()\nawait session.refresh(post)\nprint(post.updated_at)\n Note
updated_at is updated by SQLAlchemy at ORM flush time. If you update rows via raw SQL (e.g. UPDATE posts SET ...), the column will not be updated automatically — use a database trigger if you need that guarantee.
TimestampMixin","text":"Convenience mixin that combines CreatedAtMixin and UpdatedAtMixin. Equivalent to inheriting both.
from fastapi_toolsets.models import UUIDMixin, TimestampMixin\n\nclass Article(Base, UUIDMixin, TimestampMixin):\n __tablename__ = \"articles\"\n\n title: Mapped[str]\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#watchedfieldsmixin","level":3,"title":"WatchedFieldsMixin","text":"Added in v2.4
WatchedFieldsMixin provides lifecycle callbacks that fire after commit — meaning the row is durably persisted when your callback runs. If the transaction rolls back, no callback fires.
Three callbacks are available, each corresponding to a ModelEvent value:
on_create() ModelEvent.CREATE After INSERT on_delete() ModelEvent.DELETE After DELETE on_update(changes) ModelEvent.UPDATE After UPDATE on a watched field Server-side defaults (e.g. id, created_at) are fully populated in all callbacks. All callbacks support both async def and plain def. Use @watch to restrict which fields trigger on_update:
on_update behaviour @watch(\"status\", \"role\") Only fires when status or role changes (no decorator) Fires when any mapped field changes @watch is inherited through the class hierarchy. If a subclass does not declare its own @watch, it uses the filter from the nearest decorated parent. Applying @watch on the subclass overrides the parent's filter:
@watch(\"status\")\nclass Order(Base, UUIDMixin, WatchedFieldsMixin):\n ...\n\nclass UrgentOrder(Order):\n # inherits @watch(\"status\") — on_update fires only for status changes\n ...\n\n@watch(\"priority\")\nclass PriorityOrder(Order):\n # overrides parent — on_update fires only for priority changes\n ...\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#option-1-catch-all-with-on_event","level":4,"title":"Option 1 — catch-all with on_event","text":"Override on_event to handle all event types in one place. The specific methods delegate here by default:
from fastapi_toolsets.models import ModelEvent, UUIDMixin, WatchedFieldsMixin, watch\n\n@watch(\"status\")\nclass Order(Base, UUIDMixin, WatchedFieldsMixin):\n __tablename__ = \"orders\"\n\n status: Mapped[str]\n\n async def on_event(self, event: ModelEvent, changes: dict | None = None) -> None:\n if event == ModelEvent.CREATE:\n await notify_new_order(self.id)\n elif event == ModelEvent.DELETE:\n await notify_order_cancelled(self.id)\n elif event == ModelEvent.UPDATE:\n await notify_status_change(self.id, changes[\"status\"])\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#option-2-targeted-overrides","level":4,"title":"Option 2 — targeted overrides","text":"Override individual methods for more focused logic:
@watch(\"status\")\nclass Order(Base, UUIDMixin, WatchedFieldsMixin):\n __tablename__ = \"orders\"\n\n status: Mapped[str]\n\n async def on_create(self) -> None:\n await notify_new_order(self.id)\n\n async def on_delete(self) -> None:\n await notify_order_cancelled(self.id)\n\n async def on_update(self, changes: dict) -> None:\n if \"status\" in changes:\n old = changes[\"status\"][\"old\"]\n new = changes[\"status\"][\"new\"]\n await notify_status_change(self.id, old, new)\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#field-changes-format","level":4,"title":"Field changes format","text":"The changes dict maps each watched field that changed to {\"old\": ..., \"new\": ...}. Only fields that actually changed are included:
# status changed → {\"status\": {\"old\": \"pending\", \"new\": \"shipped\"}}\n# two fields changed → {\"status\": {...}, \"assigned_to\": {...}}\n Multiple flushes in one transaction are merged: the earliest old and latest new are preserved, and on_update fires only once per commit.
Callbacks fire only for ORM-level changes. Rows updated via raw SQL (UPDATE ... SET ...) are not detected.
Callbacks fire when the outermost active context (savepoint or transaction) commits.
If you create several related objects using CrudFactory.create and need callbacks to see all of them (including associations), wrap the whole operation in a single get_transaction or lock_tables block. Without it, each create call commits its own savepoint and on_create fires before the remaining objects exist.
from fastapi_toolsets.db import get_transaction\n\nasync with get_transaction(session):\n order = await OrderCrud.create(session, order_data)\n item = await ItemCrud.create(session, item_data)\n await session.refresh(order, attribute_names=[\"items\"])\n order.items.append(item)\n# on_create fires here for both order and item,\n# with the full association already committed.\n","path":["Modules","Models"],"tags":[]},{"location":"module/models/#composing-mixins","level":2,"title":"Composing mixins","text":"All mixins can be combined in any order. The only constraint is that exactly one primary key must be defined — either via UUIDMixin or directly on the model.
from fastapi_toolsets.models import UUIDMixin, TimestampMixin\n\nclass Event(Base, UUIDMixin, TimestampMixin):\n __tablename__ = \"events\"\n name: Mapped[str]\n\nclass Counter(Base, UpdatedAtMixin):\n __tablename__ = \"counters\"\n id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)\n value: Mapped[int]\n API Reference
","path":["Modules","Models"],"tags":[]},{"location":"module/pytest/","level":1,"title":"Pytest","text":"Testing helpers for FastAPI applications with async client, database sessions, and parallel worker support.
","path":["Modules","Pytest"],"tags":[]},{"location":"module/pytest/#installation","level":2,"title":"Installation","text":"uvpipuv add \"fastapi-toolsets[pytest]\"\n pip install \"fastapi-toolsets[pytest]\"\n","path":["Modules","Pytest"],"tags":[]},{"location":"module/pytest/#overview","level":2,"title":"Overview","text":"The pytest module provides utilities for setting up async test clients, managing test database sessions, and supporting parallel test execution with pytest-xdist.
Use create_async_client to get an httpx.AsyncClient configured for your FastAPI app:
from fastapi_toolsets.pytest import create_async_client\n\n@pytest.fixture\nasync def http_client(db_session):\n async def _override_get_db():\n yield db_session\n\n async with create_async_client(\n app=app,\n base_url=\"http://127.0.0.1/api/v1\",\n dependency_overrides={get_db: _override_get_db},\n ) as c:\n yield c\n","path":["Modules","Pytest"],"tags":[]},{"location":"module/pytest/#database-sessions-in-tests","level":2,"title":"Database sessions in tests","text":"Use create_db_session to create an isolated AsyncSession for a test, combined with create_worker_database to set up a per-worker database:
from fastapi_toolsets.pytest import create_worker_database, create_db_session\n\n@pytest.fixture(scope=\"session\")\nasync def worker_db_url():\n async with create_worker_database(\n database_url=str(settings.SQLALCHEMY_DATABASE_URI)\n ) as url:\n yield url\n\n\n@pytest.fixture\nasync def db_session(worker_db_url):\n async with create_db_session(\n database_url=worker_db_url, base=Base, cleanup=True\n ) as session:\n yield session\n Info
In this example, the database is reset between each test using the argument cleanup=True.
Use worker_database_url to derive the per-worker URL manually if needed:
from fastapi_toolsets.pytest import worker_database_url\n\nurl = worker_database_url(\"postgresql+asyncpg://user:pass@localhost/test_db\", default_test_db=\"test\")\n# e.g. \"postgresql+asyncpg://user:pass@localhost/test_db_gw0\" under xdist\n","path":["Modules","Pytest"],"tags":[]},{"location":"module/pytest/#parallel-testing-with-pytest-xdist","level":2,"title":"Parallel testing with pytest-xdist","text":"The examples above are already compatible with parallel test execution with pytest-xdist.
Warning
Since V2.1.0 cleanup_tables now live in fastapi_toolsets.db. For backward compatibility the function is still available in fastapi_toolsets.pytest, but this will be remove in V3.0.0.
If you want to manually clean up a database you can use cleanup_tables, this will truncate all tables between tests for fast isolation:
from fastapi_toolsets.db import cleanup_tables\n\n@pytest.fixture(autouse=True)\nasync def clean(db_session):\n yield\n await cleanup_tables(session=db_session, base=Base)\n API Reference
","path":["Modules","Pytest"],"tags":[]},{"location":"module/schemas/","level":1,"title":"Schemas","text":"Standardized Pydantic response models for consistent API responses across your FastAPI application.
","path":["Modules","Schemas"],"tags":[]},{"location":"module/schemas/#overview","level":2,"title":"Overview","text":"The schemas module provides generic response wrappers that enforce a uniform response structure. All models use from_attributes=True for ORM compatibility and validate_assignment=True for runtime type safety.
Response[T]","text":"The most common wrapper for a single resource response.
from fastapi_toolsets.schemas import Response\n\n@router.get(\"/users/{id}\")\nasync def get_user(user: User = UserDep) -> Response[UserSchema]:\n return Response(data=user, message=\"User retrieved\")\n","path":["Modules","Schemas"],"tags":[]},{"location":"module/schemas/#paginated-response-models","level":3,"title":"Paginated response models","text":"Three classes wrap paginated list results. Pick the one that matches your endpoint's strategy:
Classpagination type pagination_type field Use when OffsetPaginatedResponse[T] OffsetPagination \"offset\" (fixed) endpoint always uses offset CursorPaginatedResponse[T] CursorPagination \"cursor\" (fixed) endpoint always uses cursor PaginatedResponse[T] OffsetPagination \\| CursorPagination — unified endpoint supporting both strategies","path":["Modules","Schemas"],"tags":[]},{"location":"module/schemas/#offsetpaginatedresponset","level":4,"title":"OffsetPaginatedResponse[T]","text":"Added in v2.3.0
Use as the return type when the endpoint always uses offset_paginate. The pagination field is guaranteed to be an OffsetPagination object; the response always includes a pagination_type: \"offset\" discriminator.
from fastapi_toolsets.schemas import OffsetPaginatedResponse\n\n@router.get(\"/users\")\nasync def list_users(\n page: int = 1,\n items_per_page: int = 20,\n) -> OffsetPaginatedResponse[UserSchema]:\n return await UserCrud.offset_paginate(\n session, page=page, items_per_page=items_per_page, schema=UserSchema\n )\n Response shape:
{\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"offset\",\n \"data\": [\"...\"],\n \"pagination\": {\n \"total_count\": 100,\n \"page\": 1,\n \"items_per_page\": 20,\n \"has_more\": true\n }\n}\n","path":["Modules","Schemas"],"tags":[]},{"location":"module/schemas/#cursorpaginatedresponset","level":4,"title":"CursorPaginatedResponse[T]","text":"Added in v2.3.0
Use as the return type when the endpoint always uses cursor_paginate. The pagination field is guaranteed to be a CursorPagination object; the response always includes a pagination_type: \"cursor\" discriminator.
from fastapi_toolsets.schemas import CursorPaginatedResponse\n\n@router.get(\"/events\")\nasync def list_events(\n cursor: str | None = None,\n items_per_page: int = 20,\n) -> CursorPaginatedResponse[EventSchema]:\n return await EventCrud.cursor_paginate(\n session, cursor=cursor, items_per_page=items_per_page, schema=EventSchema\n )\n Response shape:
{\n \"status\": \"SUCCESS\",\n \"pagination_type\": \"cursor\",\n \"data\": [\"...\"],\n \"pagination\": {\n \"next_cursor\": \"eyJpZCI6IDQyfQ==\",\n \"prev_cursor\": null,\n \"items_per_page\": 20,\n \"has_more\": true\n }\n}\n","path":["Modules","Schemas"],"tags":[]},{"location":"module/schemas/#paginatedresponset","level":4,"title":"PaginatedResponse[T]","text":"Return type for endpoints that support both pagination strategies via a pagination_type query parameter (using paginate()).
When used as a return annotation, PaginatedResponse[T] automatically expands to Annotated[Union[CursorPaginatedResponse[T], OffsetPaginatedResponse[T]], Field(discriminator=\"pagination_type\")], so FastAPI emits a proper oneOf + discriminator in the OpenAPI schema with no extra boilerplate:
from fastapi_toolsets.crud import PaginationType\nfrom fastapi_toolsets.schemas import PaginatedResponse\n\n@router.get(\"/users\")\nasync def list_users(\n pagination_type: PaginationType = PaginationType.OFFSET,\n page: int = 1,\n cursor: str | None = None,\n items_per_page: int = 20,\n) -> PaginatedResponse[UserSchema]:\n return await UserCrud.paginate(\n session,\n pagination_type=pagination_type,\n page=page,\n cursor=cursor,\n items_per_page=items_per_page,\n schema=UserSchema,\n )\n","path":["Modules","Schemas"],"tags":[]},{"location":"module/schemas/#pagination-metadata-models","level":4,"title":"Pagination metadata models","text":"The optional filter_attributes field is populated when facet_fields are configured on the CRUD class (see Filter attributes). It is None by default and can be hidden from API responses with response_model_exclude_none=True.
ErrorResponse","text":"Returned automatically by the exceptions handler.
API Reference
","path":["Modules","Schemas"],"tags":[]},{"location":"reference/cli/","level":1,"title":"cli","text":"Here's the reference for the CLI configuration helpers used to load settings from pyproject.toml.
You can import them directly from fastapi_toolsets.cli.config:
from fastapi_toolsets.cli.config import (\n import_from_string,\n get_config_value,\n get_fixtures_registry,\n get_db_context,\n get_custom_cli,\n)\n","path":["Reference","cli"],"tags":[]},{"location":"reference/cli/#fastapi_toolsets.cli.config.import_from_string","level":2,"title":"fastapi_toolsets.cli.config.import_from_string(import_path)","text":"Import an object from a dotted string path.
Parameters:
Name Type Description Defaultimport_path str Import path in \"module.submodule:attribute\" format
Returns:
Type DescriptionAny The imported attribute
Raises:
Type DescriptionBadParameter If the import path is invalid or import fails
","path":["Reference","cli"],"tags":[]},{"location":"reference/cli/#fastapi_toolsets.cli.config.get_config_value","level":2,"title":"fastapi_toolsets.cli.config.get_config_value(key, required=False)","text":"get_config_value(key: str, required: Literal[True]) -> Any\nget_config_value(\n key: str, required: bool = False\n) -> Any | None\n Get a configuration value from pyproject.toml.
Parameters:
Name Type Description Defaultkey str The configuration key in [tool.fastapi-toolsets].
requiredrequired bool If True, raises an error when the key is missing.
False Returns:
Type DescriptionAny | None The configuration value, or None if not found and not required.
Raises:
Type DescriptionBadParameter If required=True and the key is missing.
","path":["Reference","cli"],"tags":[]},{"location":"reference/cli/#fastapi_toolsets.cli.config.get_fixtures_registry","level":2,"title":"fastapi_toolsets.cli.config.get_fixtures_registry()","text":"Import and return the fixtures registry from config.
","path":["Reference","cli"],"tags":[]},{"location":"reference/cli/#fastapi_toolsets.cli.config.get_db_context","level":2,"title":"fastapi_toolsets.cli.config.get_db_context()","text":"Import and return the db_context function from config.
","path":["Reference","cli"],"tags":[]},{"location":"reference/cli/#fastapi_toolsets.cli.config.get_custom_cli","level":2,"title":"fastapi_toolsets.cli.config.get_custom_cli()","text":"Import and return the custom CLI Typer instance from config.
","path":["Reference","cli"],"tags":[]},{"location":"reference/cli/#fastapi_toolsets.cli.utils.async_command","level":2,"title":"fastapi_toolsets.cli.utils.async_command(func)","text":"Decorator to run an async function as a sync CLI command.
Example@fixture_cli.command(\"load\")\n@async_command\nasync def load(ctx: typer.Context) -> None:\n async with get_db_context() as session:\n await load_fixtures(session, registry)\n","path":["Reference","cli"],"tags":[]},{"location":"reference/crud/","level":1,"title":"crud","text":"Here's the reference for the CRUD classes, factory, and search utilities.
You can import the main symbols from fastapi_toolsets.crud:
from fastapi_toolsets.crud import CrudFactory, AsyncCrud\nfrom fastapi_toolsets.crud.search import SearchConfig, get_searchable_fields, build_search_filters\n","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud","level":2,"title":"fastapi_toolsets.crud.factory.AsyncCrud","text":" Bases: Generic[ModelType]
Generic async CRUD operations for SQLAlchemy models.
Subclass this and set the model class variable, or use CrudFactory.
count(session, filters=None, *, joins=None, outer_join=False) async classmethod","text":"Count records matching the filters.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] | None List of SQLAlchemy filter conditions
None joins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False Returns:
Type Descriptionint Number of matching records
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.create","level":3,"title":"create(session, obj, *, schema=None) async classmethod","text":"create(\n session: AsyncSession,\n obj: BaseModel,\n *,\n schema: type[SchemaType],\n) -> Response[SchemaType]\ncreate(\n session: AsyncSession,\n obj: BaseModel,\n *,\n schema: None = ...,\n) -> ModelType\n Create a new record in the database.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredobj BaseModel Pydantic model with data to create
requiredschema type[BaseModel] | None Pydantic schema to serialize the result into. When provided, the result is automatically wrapped in a Response[schema].
None Returns:
Type DescriptionModelType | Response[Any] Created model instance, or Response[schema] when schema is given.
cursor_paginate(session, *, cursor=None, filters=None, joins=None, outer_join=False, load_options=None, order_by=None, items_per_page=20, search=None, search_fields=None, facet_fields=None, filter_by=None, schema) async classmethod","text":"Get paginated results using cursor-based pagination.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session.
requiredcursor str | None Cursor string from a previous CursorPagination. Omit (or pass None) to start from the beginning.
None filters list[Any] | None List of SQLAlchemy filter conditions.
None joins JoinType | None List of (model, condition) tuples for joining related tables.
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN.
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options. Falls back to default_load_options when not provided.
None order_by OrderByClause | None Additional ordering applied after the cursor column.
None items_per_page int Number of items per page (default 20).
20 search str | SearchConfig | None Search query string or SearchConfig object.
None search_fields Sequence[SearchFieldType] | None Fields to search in (overrides class default).
None facet_fields Sequence[FacetFieldType] | None Columns to compute distinct values for (overrides class default).
None filter_by dict[str, Any] | BaseModel | None Dict of {column_key: value} to filter by declared facet fields. Keys must match the column.key of a facet field. Scalar → equality, list → IN clause. Raises InvalidFacetFilterError for unknown keys.
None schema type[BaseModel] Optional Pydantic schema to serialize each item into.
requiredReturns:
Type DescriptionCursorPaginatedResponse[Any] PaginatedResponse with CursorPagination metadata
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.cursor_params","level":3,"title":"cursor_params(*, default_page_size=20, max_page_size=100) classmethod","text":"Return a FastAPI dependency that collects cursor pagination params from query params.
Parameters:
Name Type Description Defaultdefault_page_size int Default value for the items_per_page query parameter.
20 max_page_size int Maximum allowed value for items_per_page (enforced via le on the Query).
100 Returns:
Type DescriptionCallable[..., Awaitable[dict[str, Any]]] An async dependency that resolves to a dict with cursor and
Callable[..., Awaitable[dict[str, Any]]] items_per_page keys, ready to be unpacked into
Callable[..., Awaitable[dict[str, Any]]] meth:cursor_paginate.
delete(session, filters, *, return_response=False) async classmethod","text":"delete(\n session: AsyncSession,\n filters: list[Any],\n *,\n return_response: Literal[True],\n) -> Response[None]\ndelete(\n session: AsyncSession,\n filters: list[Any],\n *,\n return_response: Literal[False] = ...,\n) -> None\n Delete records from the database.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] List of SQLAlchemy filter conditions
requiredreturn_response bool When True, returns Response[None] instead of None. Useful for API endpoints that expect a consistent response envelope.
False Returns:
Type DescriptionNone | Response[None] None, or Response[None] when return_response=True.
exists(session, filters, *, joins=None, outer_join=False) async classmethod","text":"Check if a record exists.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] List of SQLAlchemy filter conditions
requiredjoins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False Returns:
Type Descriptionbool True if at least one record matches
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.filter_params","level":3,"title":"filter_params(*, facet_fields=None) classmethod","text":"Return a FastAPI dependency that collects facet filter values from query parameters.
Parameters:
Name Type Description Defaultfacet_fields Sequence[FacetFieldType] | None Override the facet fields for this dependency. Falls back to the class-level facet_fields if not provided.
None Returns:
Type DescriptionCallable[..., Awaitable[dict[str, list[str]]]] An async dependency function named {Model}FilterParams that resolves to a
Callable[..., Awaitable[dict[str, list[str]]]] dict[str, list[str]] containing only the keys that were supplied in the
Callable[..., Awaitable[dict[str, list[str]]]] request (absent/None parameters are excluded).
Raises:
Type DescriptionValueError If no facet fields are configured on this CRUD class and none are provided via facet_fields.
first(session, filters=None, *, joins=None, outer_join=False, with_for_update=False, load_options=None, schema=None) async classmethod","text":"first(\n session: AsyncSession,\n filters: list[Any] | None = None,\n *,\n joins: JoinType | None = None,\n outer_join: bool = False,\n with_for_update: bool = False,\n load_options: Sequence[ExecutableOption] | None = None,\n schema: type[SchemaType],\n) -> Response[SchemaType] | None\nfirst(\n session: AsyncSession,\n filters: list[Any] | None = None,\n *,\n joins: JoinType | None = None,\n outer_join: bool = False,\n with_for_update: bool = False,\n load_options: Sequence[ExecutableOption] | None = None,\n schema: None = ...,\n) -> ModelType | None\n Get the first matching record, or None.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] | None List of SQLAlchemy filter conditions
None joins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False with_for_update bool Lock the row for update
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options (e.g., selectinload)
None schema type[BaseModel] | None Pydantic schema to serialize the result into. When provided, the result is automatically wrapped in a Response[schema].
None Returns:
Type DescriptionModelType | Response[Any] | None Model instance, Response[schema] when schema is given,
ModelType | Response[Any] | None or None when no record matches.
get(session, filters, *, joins=None, outer_join=False, with_for_update=False, load_options=None, schema=None) async classmethod","text":"get(\n session: AsyncSession,\n filters: list[Any],\n *,\n joins: JoinType | None = None,\n outer_join: bool = False,\n with_for_update: bool = False,\n load_options: Sequence[ExecutableOption] | None = None,\n schema: type[SchemaType],\n) -> Response[SchemaType]\nget(\n session: AsyncSession,\n filters: list[Any],\n *,\n joins: JoinType | None = None,\n outer_join: bool = False,\n with_for_update: bool = False,\n load_options: Sequence[ExecutableOption] | None = None,\n schema: None = ...,\n) -> ModelType\n Get exactly one record. Raises NotFoundError if not found.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] List of SQLAlchemy filter conditions
requiredjoins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False with_for_update bool Lock the row for update
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options (e.g., selectinload)
None schema type[BaseModel] | None Pydantic schema to serialize the result into. When provided, the result is automatically wrapped in a Response[schema].
None Returns:
Type DescriptionModelType | Response[Any] Model instance, or Response[schema] when schema is given.
Raises:
Type DescriptionNotFoundError If no record found
MultipleResultsFound If more than one record found
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.get_multi","level":3,"title":"get_multi(session, *, filters=None, joins=None, outer_join=False, load_options=None, order_by=None, limit=None, offset=None) async classmethod","text":"Get multiple records from the database.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] | None List of SQLAlchemy filter conditions
None joins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options
None order_by OrderByClause | None Column or list of columns to order by
None limit int | None Max number of rows to return
None offset int | None Rows to skip
None Returns:
Type DescriptionSequence[ModelType] List of model instances
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.get_or_none","level":3,"title":"get_or_none(session, filters, *, joins=None, outer_join=False, with_for_update=False, load_options=None, schema=None) async classmethod","text":"get_or_none(\n session: AsyncSession,\n filters: list[Any],\n *,\n joins: JoinType | None = None,\n outer_join: bool = False,\n with_for_update: bool = False,\n load_options: Sequence[ExecutableOption] | None = None,\n schema: type[SchemaType],\n) -> Response[SchemaType] | None\nget_or_none(\n session: AsyncSession,\n filters: list[Any],\n *,\n joins: JoinType | None = None,\n outer_join: bool = False,\n with_for_update: bool = False,\n load_options: Sequence[ExecutableOption] | None = None,\n schema: None = ...,\n) -> ModelType | None\n Get exactly one record, or None if not found.
Like :meth:get but returns None instead of raising :class:~fastapi_toolsets.exceptions.NotFoundError when no record matches the filters.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] List of SQLAlchemy filter conditions
requiredjoins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False with_for_update bool Lock the row for update
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options (e.g., selectinload)
None schema type[BaseModel] | None Pydantic schema to serialize the result into. When provided, the result is automatically wrapped in a Response[schema].
None Returns:
Type DescriptionModelType | Response[Any] | None Model instance, Response[schema] when schema is given,
ModelType | Response[Any] | None or None when no record matches.
Raises:
Type DescriptionMultipleResultsFound If more than one record found
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.offset_paginate","level":3,"title":"offset_paginate(session, *, filters=None, joins=None, outer_join=False, load_options=None, order_by=None, page=1, items_per_page=20, include_total=True, search=None, search_fields=None, facet_fields=None, filter_by=None, schema) async classmethod","text":"Get paginated results using offset-based pagination.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredfilters list[Any] | None List of SQLAlchemy filter conditions
None joins JoinType | None List of (model, condition) tuples for joining related tables
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options
None order_by OrderByClause | None Column or list of columns to order by
None page int Page number (1-indexed)
1 items_per_page int Number of items per page
20 include_total bool When False, skip the COUNT query; pagination.total_count will be None.
True search str | SearchConfig | None Search query string or SearchConfig object
None search_fields Sequence[SearchFieldType] | None Fields to search in (overrides class default)
None facet_fields Sequence[FacetFieldType] | None Columns to compute distinct values for (overrides class default)
None filter_by dict[str, Any] | BaseModel | None Dict of {column_key: value} to filter by declared facet fields. Keys must match the column.key of a facet field. Scalar → equality, list → IN clause. Raises InvalidFacetFilterError for unknown keys.
None schema type[BaseModel] Pydantic schema to serialize each item into.
requiredReturns:
Type DescriptionOffsetPaginatedResponse[Any] PaginatedResponse with OffsetPagination metadata
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.offset_params","level":3,"title":"offset_params(*, default_page_size=20, max_page_size=100, include_total=True) classmethod","text":"Return a FastAPI dependency that collects offset pagination params from query params.
Parameters:
Name Type Description Defaultdefault_page_size int Default value for the items_per_page query parameter.
20 max_page_size int Maximum allowed value for items_per_page (enforced via le on the Query).
100 include_total bool Server-side flag forwarded as-is to include_total in :meth:offset_paginate. Not exposed as a query parameter.
True Returns:
Type DescriptionCallable[..., Awaitable[dict[str, Any]]] An async dependency that resolves to a dict with page,
Callable[..., Awaitable[dict[str, Any]]] items_per_page, and include_total keys, ready to be
Callable[..., Awaitable[dict[str, Any]]] unpacked into :meth:offset_paginate.
order_params(*, order_fields=None, default_field=None, default_order='asc') classmethod","text":"Return a FastAPI dependency that resolves order query params into an order_by clause.
Parameters:
Name Type Description Defaultorder_fields Sequence[QueryableAttribute[Any]] | None Override the allowed order fields. Falls back to the class-level order_fields if not provided.
None default_field QueryableAttribute[Any] | None Field to order by when order_by query param is absent. If None and no order_by is provided, no ordering is applied.
None default_order Literal['asc', 'desc'] Default order direction when order is absent (\"asc\" or \"desc\").
'asc' Returns:
Type DescriptionCallable[..., Awaitable[OrderByClause | None]] An async dependency function named {Model}OrderParams that resolves to an
Callable[..., Awaitable[OrderByClause | None]] OrderByClause (or None). Pass it to Depends() in your route.
Raises:
Type DescriptionValueError If no order fields are configured on this CRUD class and none are provided via order_fields.
InvalidOrderFieldError When the request provides an unknown order_by value.
paginate(session, *, pagination_type=PaginationType.OFFSET, filters=None, joins=None, outer_join=False, load_options=None, order_by=None, page=1, cursor=None, items_per_page=20, include_total=True, search=None, search_fields=None, facet_fields=None, filter_by=None, schema) async classmethod","text":"paginate(\n session: AsyncSession,\n *,\n pagination_type: Literal[PaginationType.OFFSET],\n filters: list[Any] | None = ...,\n joins: JoinType | None = ...,\n outer_join: bool = ...,\n load_options: Sequence[ExecutableOption] | None = ...,\n order_by: OrderByClause | None = ...,\n page: int = ...,\n cursor: str | None = ...,\n items_per_page: int = ...,\n include_total: bool = ...,\n search: str | SearchConfig | None = ...,\n search_fields: Sequence[SearchFieldType] | None = ...,\n facet_fields: Sequence[FacetFieldType] | None = ...,\n filter_by: dict[str, Any] | BaseModel | None = ...,\n schema: type[BaseModel],\n) -> OffsetPaginatedResponse[Any]\npaginate(\n session: AsyncSession,\n *,\n pagination_type: Literal[PaginationType.CURSOR],\n filters: list[Any] | None = ...,\n joins: JoinType | None = ...,\n outer_join: bool = ...,\n load_options: Sequence[ExecutableOption] | None = ...,\n order_by: OrderByClause | None = ...,\n page: int = ...,\n cursor: str | None = ...,\n items_per_page: int = ...,\n include_total: bool = ...,\n search: str | SearchConfig | None = ...,\n search_fields: Sequence[SearchFieldType] | None = ...,\n facet_fields: Sequence[FacetFieldType] | None = ...,\n filter_by: dict[str, Any] | BaseModel | None = ...,\n schema: type[BaseModel],\n) -> CursorPaginatedResponse[Any]\n Get paginated results using either offset or cursor pagination.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session.
requiredpagination_type PaginationType Pagination strategy. Defaults to PaginationType.OFFSET.
OFFSET filters list[Any] | None List of SQLAlchemy filter conditions.
None joins JoinType | None List of (model, condition) tuples for joining related tables.
None outer_join bool Use LEFT OUTER JOIN instead of INNER JOIN.
False load_options Sequence[ExecutableOption] | None SQLAlchemy loader options. Falls back to default_load_options when not provided.
None order_by OrderByClause | None Column or expression to order results by.
None page int Page number (1-indexed). Only used when pagination_type is OFFSET.
1 cursor str | None Cursor token from a previous :class:.CursorPaginatedResponse. Only used when pagination_type is CURSOR.
None items_per_page int Number of items per page (default 20).
20 include_total bool When False, skip the COUNT query; only applies when pagination_type is OFFSET.
True search str | SearchConfig | None Search query string or :class:.SearchConfig object.
None search_fields Sequence[SearchFieldType] | None Fields to search in (overrides class default).
None facet_fields Sequence[FacetFieldType] | None Columns to compute distinct values for (overrides class default).
None filter_by dict[str, Any] | BaseModel | None Dict of {column_key: value} to filter by declared facet fields. Keys must match the column.key of a facet field. Scalar → equality, list → IN clause. Raises :exc:.InvalidFacetFilterError for unknown keys.
None schema type[BaseModel] Pydantic schema to serialize each item into.
requiredReturns:
Type DescriptionOffsetPaginatedResponse[Any] | CursorPaginatedResponse[Any] class:.OffsetPaginatedResponse when pagination_type is
OffsetPaginatedResponse[Any] | CursorPaginatedResponse[Any] OFFSET, :class:.CursorPaginatedResponse when it is
OffsetPaginatedResponse[Any] | CursorPaginatedResponse[Any] CURSOR.
paginate_params(*, default_page_size=20, max_page_size=100, default_pagination_type=PaginationType.OFFSET, include_total=True) classmethod","text":"Return a FastAPI dependency that collects all pagination params from query params.
Parameters:
Name Type Description Defaultdefault_page_size int Default value for the items_per_page query parameter.
20 max_page_size int Maximum allowed value for items_per_page (enforced via le on the Query).
100 default_pagination_type PaginationType Default pagination strategy.
OFFSET include_total bool Server-side flag forwarded as-is to include_total in :meth:paginate. Not exposed as a query parameter.
True Returns:
Type DescriptionCallable[..., Awaitable[dict[str, Any]]] An async dependency that resolves to a dict with pagination_type,
Callable[..., Awaitable[dict[str, Any]]] page, cursor, items_per_page, and include_total keys,
Callable[..., Awaitable[dict[str, Any]]] ready to be unpacked into :meth:paginate.
update(session, obj, filters, *, exclude_unset=True, exclude_none=False, schema=None) async classmethod","text":"update(\n session: AsyncSession,\n obj: BaseModel,\n filters: list[Any],\n *,\n exclude_unset: bool = True,\n exclude_none: bool = False,\n schema: type[SchemaType],\n) -> Response[SchemaType]\nupdate(\n session: AsyncSession,\n obj: BaseModel,\n filters: list[Any],\n *,\n exclude_unset: bool = True,\n exclude_none: bool = False,\n schema: None = ...,\n) -> ModelType\n Update a record in the database.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredobj BaseModel Pydantic model with update data
requiredfilters list[Any] List of SQLAlchemy filter conditions
requiredexclude_unset bool Exclude fields not explicitly set in the schema
True exclude_none bool Exclude fields with None value
False schema type[BaseModel] | None Pydantic schema to serialize the result into. When provided, the result is automatically wrapped in a Response[schema].
None Returns:
Type DescriptionModelType | Response[Any] Updated model instance, or Response[schema] when schema is given.
Raises:
Type DescriptionNotFoundError If no record found
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.AsyncCrud.upsert","level":3,"title":"upsert(session, obj, index_elements, *, set_=None, where=None) async classmethod","text":"Create or update a record (PostgreSQL only).
Uses INSERT ... ON CONFLICT for atomic upsert.
Parameters:
Name Type Description Defaultsession AsyncSession DB async session
requiredobj BaseModel Pydantic model with data
requiredindex_elements list[str] Columns for ON CONFLICT (unique constraint)
requiredset_ BaseModel | None Pydantic model for ON CONFLICT DO UPDATE SET
None where WhereHavingRole | None WHERE clause for ON CONFLICT DO UPDATE
None Returns:
Type DescriptionModelType | None Model instance
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.factory.CrudFactory","level":2,"title":"fastapi_toolsets.crud.factory.CrudFactory(model, *, base_class=AsyncCrud, searchable_fields=None, facet_fields=None, order_fields=None, m2m_fields=None, default_load_options=None, cursor_column=None)","text":"Create a CRUD class for a specific model.
Parameters:
Name Type Description Defaultmodel type[ModelType] SQLAlchemy model class
requiredbase_class type[AsyncCrud[Any]] Optional base class to inherit from instead of AsyncCrud. Use this to share custom methods across multiple CRUD classes while still using the factory shorthand.
AsyncCrud searchable_fields Sequence[SearchFieldType] | None Optional list of searchable fields
None facet_fields Sequence[FacetFieldType] | None Optional list of columns to compute distinct values for in paginated responses. Supports direct columns (User.status) and relationship tuples ((User.role, Role.name)). Can be overridden per call.
None order_fields Sequence[QueryableAttribute[Any]] | None Optional list of model attributes that callers are allowed to order by via order_params(). Can be overridden per call.
None m2m_fields M2MFieldType | None Optional mapping for many-to-many relationships. Maps schema field names (containing lists of IDs) to SQLAlchemy relationship attributes.
None default_load_options Sequence[ExecutableOption] | None Default SQLAlchemy loader options applied to all read queries when no explicit load_options are passed. Use this instead of lazy=\"selectin\" on the model so that loading strategy is explicit and per-CRUD. Overridden entirely (not merged) when load_options is provided at call-site.
None cursor_column Any | None Required to call cursor_paginate. Must be monotonically ordered (e.g. integer PK, UUID v7, timestamp). See the cursor pagination docs for supported column types.
None Returns:
Type Descriptiontype[AsyncCrud[ModelType]] AsyncCrud subclass bound to the model
Examplefrom fastapi_toolsets.crud import CrudFactory\nfrom myapp.models import User, Post\n\nUserCrud = CrudFactory(User)\nPostCrud = CrudFactory(Post)\n\n# With searchable fields:\nUserCrud = CrudFactory(\n User,\n searchable_fields=[User.username, User.email, (User.role, Role.name)]\n)\n\n# With many-to-many fields:\n# Schema has `tag_ids: list[UUID]`, model has `tags` relationship to Tag\nPostCrud = CrudFactory(\n Post,\n m2m_fields={\"tag_ids\": Post.tags},\n)\n\n# With facet fields for filter dropdowns / faceted search:\nUserCrud = CrudFactory(\n User,\n facet_fields=[User.status, User.country, (User.role, Role.name)],\n)\n\n# With a fixed cursor column for cursor_paginate:\nPostCrud = CrudFactory(\n Post,\n cursor_column=Post.created_at,\n)\n\n# With default load strategy (replaces lazy=\"selectin\" on the model):\nArticleCrud = CrudFactory(\n Article,\n default_load_options=[selectinload(Article.category), selectinload(Article.tags)],\n)\n\n# Override default_load_options for a specific call:\narticle = await ArticleCrud.get(\n session,\n [Article.id == 1],\n load_options=[selectinload(Article.category)], # tags won't load\n)\n\n# Usage\nuser = await UserCrud.get(session, [User.id == 1])\nposts = await PostCrud.get_multi(session, filters=[Post.user_id == user.id])\n\n# Create with M2M - tag_ids are automatically resolved\npost = await PostCrud.create(session, PostCreate(title=\"Hello\", tag_ids=[id1, id2]))\n\n# With search\nresult = await UserCrud.offset_paginate(session, search=\"john\")\n\n# With joins (inner join by default):\nusers = await UserCrud.get_multi(\n session,\n joins=[(Post, Post.user_id == User.id)],\n filters=[Post.published == True],\n)\n\n# With outer join:\nusers = await UserCrud.get_multi(\n session,\n joins=[(Post, Post.user_id == User.id)],\n outer_join=True,\n)\n\n# With a shared custom base class:\nfrom typing import Generic, TypeVar\nfrom sqlalchemy.orm import DeclarativeBase\n\nT = TypeVar(\"T\", bound=DeclarativeBase)\n\nclass AuditedCrud(AsyncCrud[T], Generic[T]):\n @classmethod\n async def get_active(cls, session):\n return await cls.get_multi(session, filters=[cls.model.is_active == True])\n\nUserCrud = CrudFactory(User, base_class=AuditedCrud)\n","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.search.SearchConfig","level":2,"title":"fastapi_toolsets.crud.search.SearchConfig dataclass","text":"Advanced search configuration.
Attributes:
Name Type Descriptionquery str The search string
fields Sequence[SearchFieldType] | None Fields to search (columns or tuples for relationships)
case_sensitive bool Case-sensitive search (default: False)
match_mode Literal['any', 'all'] \"any\" (OR) or \"all\" (AND) to combine fields
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.search.get_searchable_fields","level":2,"title":"fastapi_toolsets.crud.search.get_searchable_fields(model, *, include_relationships=True, max_depth=1) cached","text":"Auto-detect String fields on a model and its relationships.
Parameters:
Name Type Description Defaultmodel type[DeclarativeBase] SQLAlchemy model class
requiredinclude_relationships bool Include fields from many-to-one/one-to-one relationships
True max_depth int Max depth for relationship traversal (default: 1)
1 Returns:
Type Descriptionlist[SearchFieldType] List of columns and tuples (relationship, column)
","path":["Reference","crud"],"tags":[]},{"location":"reference/crud/#fastapi_toolsets.crud.search.build_search_filters","level":2,"title":"fastapi_toolsets.crud.search.build_search_filters(model, search, search_fields=None, default_fields=None)","text":"Build SQLAlchemy filter conditions for search.
Parameters:
Name Type Description Defaultmodel type[DeclarativeBase] SQLAlchemy model class
requiredsearch str | SearchConfig Search string or SearchConfig
requiredsearch_fields Sequence[SearchFieldType] | None Fields specified per-call (takes priority)
None default_fields Sequence[SearchFieldType] | None Default fields (from ClassVar)
None Returns:
Type Descriptiontuple[list[ColumnElement[bool]], list[InstrumentedAttribute[Any]]] Tuple of (filter_conditions, joins_needed)
Raises:
Type DescriptionNoSearchableFieldsError If no searchable field has been configured
","path":["Reference","crud"],"tags":[]},{"location":"reference/db/","level":1,"title":"db","text":"Here's the reference for all database session utilities, transaction helpers, and locking functions.
You can import them directly from fastapi_toolsets.db:
from fastapi_toolsets.db import (\n LockMode,\n cleanup_tables,\n create_database,\n create_db_dependency,\n create_db_context,\n get_transaction,\n lock_tables,\n wait_for_row_change,\n)\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.LockMode","level":2,"title":"fastapi_toolsets.db.LockMode","text":" Bases: str, Enum
PostgreSQL table lock modes.
See: https://www.postgresql.org/docs/current/explicit-locking.html
","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.create_db_dependency","level":2,"title":"fastapi_toolsets.db.create_db_dependency(session_maker)","text":"Create a FastAPI dependency for database sessions.
Creates a dependency function that yields a session and auto-commits if a transaction is active when the request completes.
Parameters:
Name Type Description Defaultsession_maker async_sessionmaker[AsyncSession] Async session factory from create_session_factory()
requiredReturns:
Type DescriptionCallable[[], AsyncGenerator[AsyncSession, None]] An async generator function usable with FastAPI's Depends()
Examplefrom fastapi import Depends\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker\nfrom fastapi_toolsets.db import create_db_dependency\n\nengine = create_async_engine(\"postgresql+asyncpg://...\")\nSessionLocal = async_sessionmaker(engine, expire_on_commit=False)\nget_db = create_db_dependency(SessionLocal)\n\n@app.get(\"/users\")\nasync def list_users(session: AsyncSession = Depends(get_db)):\n ...\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.create_db_context","level":2,"title":"fastapi_toolsets.db.create_db_context(session_maker)","text":"Create a context manager for database sessions.
Creates a context manager for use outside of FastAPI request handlers, such as in background tasks, CLI commands, or tests.
Parameters:
Name Type Description Defaultsession_maker async_sessionmaker[AsyncSession] Async session factory from create_session_factory()
requiredReturns:
Type DescriptionCallable[[], AbstractAsyncContextManager[AsyncSession]] An async context manager function
Examplefrom sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker\nfrom fastapi_toolsets.db import create_db_context\n\nengine = create_async_engine(\"postgresql+asyncpg://...\")\nSessionLocal = async_sessionmaker(engine, expire_on_commit=False)\nget_db_context = create_db_context(SessionLocal)\n\nasync def background_task():\n async with get_db_context() as session:\n user = await UserCrud.get(session, [User.id == 1])\n ...\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.get_transaction","level":2,"title":"fastapi_toolsets.db.get_transaction(session) async","text":"Get a transaction context, handling nested transactions.
If already in a transaction, creates a savepoint (nested transaction). Otherwise, starts a new transaction.
Parameters:
Name Type Description Defaultsession AsyncSession AsyncSession instance
requiredYields:
Type DescriptionAsyncGenerator[AsyncSession, None] The session within the transaction context
Exampleasync with get_transaction(session):\n session.add(model)\n # Auto-commits on exit, rolls back on exception\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.lock_tables","level":2,"title":"fastapi_toolsets.db.lock_tables(session, tables, *, mode=LockMode.SHARE_UPDATE_EXCLUSIVE, timeout='5s') async","text":"Lock PostgreSQL tables for the duration of a transaction.
Acquires table-level locks that are held until the transaction ends. Useful for preventing concurrent modifications during critical operations.
Parameters:
Name Type Description Defaultsession AsyncSession AsyncSession instance
requiredtables list[type[DeclarativeBase]] List of SQLAlchemy model classes to lock
requiredmode LockMode Lock mode (default: SHARE UPDATE EXCLUSIVE)
SHARE_UPDATE_EXCLUSIVE timeout str Lock timeout (default: \"5s\")
'5s' Yields:
Type DescriptionAsyncGenerator[AsyncSession, None] The session with locked tables
Raises:
Type DescriptionSQLAlchemyError If lock cannot be acquired within timeout
Examplefrom fastapi_toolsets.db import lock_tables, LockMode\n\nasync with lock_tables(session, [User, Account]):\n # Tables are locked with SHARE UPDATE EXCLUSIVE mode\n user = await UserCrud.get(session, [User.id == 1])\n user.balance += 100\n\n# With custom lock mode\nasync with lock_tables(session, [Order], mode=LockMode.EXCLUSIVE):\n # Exclusive lock - no other transactions can access\n await process_order(session, order_id)\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.wait_for_row_change","level":2,"title":"fastapi_toolsets.db.wait_for_row_change(session, model, pk_value, *, columns=None, interval=0.5, timeout=None) async","text":"Poll a database row until a change is detected.
Queries the row every interval seconds and returns the model instance once a change is detected in any column (or only the specified columns).
Parameters:
Name Type Description Defaultsession AsyncSession AsyncSession instance
requiredmodel type[_M] SQLAlchemy model class
requiredpk_value Any Primary key value of the row to watch
requiredcolumns list[str] | None Optional list of column names to watch. If None, all columns are watched.
None interval float Polling interval in seconds (default: 0.5)
0.5 timeout float | None Maximum time to wait in seconds. None means wait forever.
None Returns:
Type Description_M The refreshed model instance with updated values
Raises:
Type DescriptionNotFoundError If the row does not exist or is deleted during polling
TimeoutError If timeout expires before a change is detected
Examplefrom fastapi_toolsets.db import wait_for_row_change\n\n# Wait for any column to change\nupdated = await wait_for_row_change(session, User, user_id)\n\n# Watch specific columns with a timeout\nupdated = await wait_for_row_change(\n session, User, user_id,\n columns=[\"status\", \"email\"],\n interval=1.0,\n timeout=30.0,\n)\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.create_database","level":2,"title":"fastapi_toolsets.db.create_database(db_name, *, server_url) async","text":"Create a database.
Connects to server_url using AUTOCOMMIT isolation and issues a CREATE DATABASE statement for db_name.
Parameters:
Name Type Description Defaultdb_name str Name of the database to create.
requiredserver_url str URL used for server-level DDL (must point to an existing database on the same server).
required Examplefrom fastapi_toolsets.db import create_database\n\nSERVER_URL = \"postgresql+asyncpg://postgres:postgres@localhost/postgres\"\nawait create_database(\"myapp_test\", server_url=SERVER_URL)\n","path":["Reference","db"],"tags":[]},{"location":"reference/db/#fastapi_toolsets.db.cleanup_tables","level":2,"title":"fastapi_toolsets.db.cleanup_tables(session, base) async","text":"Truncate all tables for fast between-test cleanup.
Executes a single TRUNCATE … RESTART IDENTITY CASCADE statement across every table in base's metadata, which is significantly faster than dropping and re-creating tables between tests.
This is a no-op when the metadata contains no tables.
Parameters:
Name Type Description Defaultsession AsyncSession An active async database session.
requiredbase type[DeclarativeBase] SQLAlchemy DeclarativeBase class containing model metadata.
required Example@pytest.fixture\nasync def db_session(worker_db_url):\n async with create_db_session(worker_db_url, Base) as session:\n yield session\n await cleanup_tables(session, Base)\n","path":["Reference","db"],"tags":[]},{"location":"reference/dependencies/","level":1,"title":"dependencies","text":"Here's the reference for the FastAPI dependency factory functions.
You can import them directly from fastapi_toolsets.dependencies:
from fastapi_toolsets.dependencies import PathDependency, BodyDependency\n","path":["Reference","dependencies"],"tags":[]},{"location":"reference/dependencies/#fastapi_toolsets.dependencies.PathDependency","level":2,"title":"fastapi_toolsets.dependencies.PathDependency(model, field, *, session_dep, param_name=None)","text":"Create a dependency that fetches a DB object from a path parameter.
Parameters:
Name Type Description Defaultmodel type[ModelType] SQLAlchemy model class
requiredfield Any Model field to filter by (e.g., User.id)
requiredsession_dep SessionDependency Session dependency function (e.g., get_db)
requiredparam_name str | None Path parameter name (defaults to model_field, e.g., user_id)
None Returns:
Type DescriptionModelType A Depends() instance that resolves to the model instance
Raises:
Type DescriptionNotFoundError If no matching record is found
ExampleUserDep = PathDependency(User, User.id, session_dep=get_db)\n\n@router.get(\"/user/{id}\")\nasync def get(\n user: User = UserDep,\n): ...\n","path":["Reference","dependencies"],"tags":[]},{"location":"reference/dependencies/#fastapi_toolsets.dependencies.BodyDependency","level":2,"title":"fastapi_toolsets.dependencies.BodyDependency(model, field, *, session_dep, body_field)","text":"Create a dependency that fetches a DB object from a body field.
Parameters:
Name Type Description Defaultmodel type[ModelType] SQLAlchemy model class
requiredfield Any Model field to filter by (e.g., User.id)
requiredsession_dep SessionDependency Session dependency function (e.g., get_db)
requiredbody_field str Name of the field in the request body
requiredReturns:
Type DescriptionModelType A Depends() instance that resolves to the model instance
Raises:
Type DescriptionNotFoundError If no matching record is found
ExampleUserDep = BodyDependency(\n User, User.ctfd_id, session_dep=get_db, body_field=\"user_id\"\n)\n\n@router.post(\"/assign\")\nasync def assign(\n user: User = UserDep,\n): ...\n","path":["Reference","dependencies"],"tags":[]},{"location":"reference/exceptions/","level":1,"title":"exceptions","text":"Here's the reference for all exception classes and handler utilities.
You can import them directly from fastapi_toolsets.exceptions:
from fastapi_toolsets.exceptions import (\n ApiException,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n ConflictError,\n NoSearchableFieldsError,\n InvalidFacetFilterError,\n InvalidOrderFieldError,\n generate_error_responses,\n init_exceptions_handlers,\n)\n","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.ApiException","level":2,"title":"fastapi_toolsets.exceptions.exceptions.ApiException","text":" Bases: Exception
Base exception for API errors with structured response.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.ApiException.__init__","level":3,"title":"__init__(detail=None, *, desc=None, data=None)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultdetail str | None Optional human-readable message
None desc str | None Optional per-instance override for the description field in the HTTP response body.
None data Any Optional per-instance override for the data field in the HTTP response body.
None","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.UnauthorizedError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.UnauthorizedError","text":" Bases: ApiException
HTTP 401 - User is not authenticated.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.UnauthorizedError.__init__","level":3,"title":"__init__(detail=None, *, desc=None, data=None)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultdetail str | None Optional human-readable message
None desc str | None Optional per-instance override for the description field in the HTTP response body.
None data Any Optional per-instance override for the data field in the HTTP response body.
None","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.ForbiddenError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.ForbiddenError","text":" Bases: ApiException
HTTP 403 - User lacks required permissions.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.ForbiddenError.__init__","level":3,"title":"__init__(detail=None, *, desc=None, data=None)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultdetail str | None Optional human-readable message
None desc str | None Optional per-instance override for the description field in the HTTP response body.
None data Any Optional per-instance override for the data field in the HTTP response body.
None","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.NotFoundError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.NotFoundError","text":" Bases: ApiException
HTTP 404 - Resource not found.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.NotFoundError.__init__","level":3,"title":"__init__(detail=None, *, desc=None, data=None)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultdetail str | None Optional human-readable message
None desc str | None Optional per-instance override for the description field in the HTTP response body.
None data Any Optional per-instance override for the data field in the HTTP response body.
None","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.ConflictError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.ConflictError","text":" Bases: ApiException
HTTP 409 - Resource conflict.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.ConflictError.__init__","level":3,"title":"__init__(detail=None, *, desc=None, data=None)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultdetail str | None Optional human-readable message
None desc str | None Optional per-instance override for the description field in the HTTP response body.
None data Any Optional per-instance override for the data field in the HTTP response body.
None","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.NoSearchableFieldsError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.NoSearchableFieldsError","text":" Bases: ApiException
Raised when search is requested but no searchable fields are available.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.NoSearchableFieldsError.__init__","level":3,"title":"__init__(model)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultmodel type The model class that has no searchable fields configured.
required","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.InvalidFacetFilterError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.InvalidFacetFilterError","text":" Bases: ApiException
Raised when filter_by contains a key not declared in facet_fields.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.InvalidFacetFilterError.__init__","level":3,"title":"__init__(key, valid_keys)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultkey str The unknown filter key provided by the caller.
requiredvalid_keys set[str] Set of valid keys derived from the declared facet_fields.
required","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.InvalidOrderFieldError","level":2,"title":"fastapi_toolsets.exceptions.exceptions.InvalidOrderFieldError","text":" Bases: ApiException
Raised when order_by contains a field not in the allowed order fields.
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.InvalidOrderFieldError.__init__","level":3,"title":"__init__(field, valid_fields)","text":"Initialize the exception.
Parameters:
Name Type Description Defaultfield str The unknown order field provided by the caller.
requiredvalid_fields list[str] List of valid field names.
required","path":["Reference","exceptions"],"tags":[]},{"location":"reference/exceptions/#fastapi_toolsets.exceptions.exceptions.generate_error_responses","level":2,"title":"fastapi_toolsets.exceptions.exceptions.generate_error_responses(*errors)","text":"Generate OpenAPI response documentation for exceptions.
Parameters:
Name Type Description Default*errors type[ApiException] Exception classes that inherit from ApiException.
() Returns:
Type Descriptiondict[int | str, dict[str, Any]] Dict suitable for FastAPI's responses parameter.
fastapi_toolsets.exceptions.handler.init_exceptions_handlers(app)","text":"Register exception handlers and custom OpenAPI schema on a FastAPI app.
Parameters:
Name Type Description Defaultapp FastAPI FastAPI application instance.
requiredReturns:
Type DescriptionFastAPI The same FastAPI instance (for chaining).
","path":["Reference","exceptions"],"tags":[]},{"location":"reference/fixtures/","level":1,"title":"fixtures","text":"Here's the reference for the fixture registry, enums, and loading utilities.
You can import them directly from fastapi_toolsets.fixtures:
from fastapi_toolsets.fixtures import (\n Context,\n LoadStrategy,\n Fixture,\n FixtureRegistry,\n load_fixtures,\n load_fixtures_by_context,\n get_obj_by_attr,\n)\n","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.Context","level":2,"title":"fastapi_toolsets.fixtures.enum.Context","text":" Bases: str, Enum
Predefined fixture contexts.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.Context.BASE","level":3,"title":"BASE = 'base' class-attribute instance-attribute","text":"Base fixtures loaded in all environments.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.Context.DEVELOPMENT","level":3,"title":"DEVELOPMENT = 'development' class-attribute instance-attribute","text":"Development fixtures.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.Context.PRODUCTION","level":3,"title":"PRODUCTION = 'production' class-attribute instance-attribute","text":"Production-only fixtures.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.Context.TESTING","level":3,"title":"TESTING = 'testing' class-attribute instance-attribute","text":"Test fixtures.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.LoadStrategy","level":2,"title":"fastapi_toolsets.fixtures.enum.LoadStrategy","text":" Bases: str, Enum
Strategy for loading fixtures into the database.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.LoadStrategy.INSERT","level":3,"title":"INSERT = 'insert' class-attribute instance-attribute","text":"Insert new records. Fails if record already exists.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.LoadStrategy.MERGE","level":3,"title":"MERGE = 'merge' class-attribute instance-attribute","text":"Insert or update based on primary key (SQLAlchemy merge).
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.enum.LoadStrategy.SKIP_EXISTING","level":3,"title":"SKIP_EXISTING = 'skip_existing' class-attribute instance-attribute","text":"Insert only if record doesn't exist (based on primary key).
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.Fixture","level":2,"title":"fastapi_toolsets.fixtures.registry.Fixture dataclass","text":"A fixture definition with metadata.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry","level":2,"title":"fastapi_toolsets.fixtures.registry.FixtureRegistry","text":"Registry for managing fixtures with dependencies.
Examplefrom fastapi_toolsets.fixtures import FixtureRegistry, Context\n\nfixtures = FixtureRegistry()\n\n@fixtures.register\ndef roles():\n return [\n Role(id=1, name=\"admin\"),\n Role(id=2, name=\"user\"),\n ]\n\n@fixtures.register(depends_on=[\"roles\"])\ndef users():\n return [\n User(id=1, username=\"admin\", role_id=1),\n ]\n\n@fixtures.register(depends_on=[\"users\"], contexts=[Context.TESTING])\ndef test_data():\n return [\n Post(id=1, title=\"Test\", user_id=1),\n ]\n","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.get","level":3,"title":"get(name)","text":"Get a fixture by name.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.get_all","level":3,"title":"get_all()","text":"Get all registered fixtures.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.get_by_context","level":3,"title":"get_by_context(*contexts)","text":"Get fixtures for specific contexts.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.include_registry","level":3,"title":"include_registry(registry)","text":"Include another FixtureRegistry in the same current FixtureRegistry.
Parameters:
Name Type Description Defaultregistry FixtureRegistry The FixtureRegistry to include
Raises:
Type DescriptionValueError If a fixture name already exists in the current registry
Exampleregistry = FixtureRegistry()\ndev_registry = FixtureRegistry()\n\n@dev_registry.register\ndef dev_data():\n return [...]\n\nregistry.include_registry(registry=dev_registry)\n","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.register","level":3,"title":"register(func=None, *, name=None, depends_on=None, contexts=None)","text":"Register a fixture function.
Can be used as a decorator with or without arguments.
Parameters:
Name Type Description Defaultfunc Callable[[], Sequence[DeclarativeBase]] | None Fixture function returning list of model instances
None name str | None Fixture name (defaults to function name)
None depends_on list[str] | None List of fixture names this depends on
None contexts list[str | Context] | None List of contexts this fixture belongs to
None Example @fixtures.register\ndef roles():\n return [Role(id=1, name=\"admin\")]\n\n@fixtures.register(depends_on=[\"roles\"], contexts=[Context.TESTING])\ndef test_users():\n return [User(id=1, username=\"test\", role_id=1)]\n","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.resolve_context_dependencies","level":3,"title":"resolve_context_dependencies(*contexts)","text":"Resolve all fixtures for contexts with dependencies.
Parameters:
Name Type Description Default*contexts str | Context Contexts to load
() Returns:
Type Descriptionlist[str] List of fixture names in load order
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.registry.FixtureRegistry.resolve_dependencies","level":3,"title":"resolve_dependencies(*names)","text":"Resolve fixture dependencies in topological order.
Parameters:
Name Type Description Default*names str Fixture names to resolve
() Returns:
Type Descriptionlist[str] List of fixture names in load order (dependencies first)
Raises:
Type DescriptionKeyError If a fixture is not found
ValueError If circular dependency detected
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.utils.load_fixtures","level":2,"title":"fastapi_toolsets.fixtures.utils.load_fixtures(session, registry, *names, strategy=LoadStrategy.MERGE) async","text":"Load specific fixtures by name with dependencies.
Parameters:
Name Type Description Defaultsession AsyncSession Database session
requiredregistry FixtureRegistry Fixture registry
required*names str Fixture names to load (dependencies auto-resolved)
() strategy LoadStrategy How to handle existing records
MERGE Returns:
Type Descriptiondict[str, list[DeclarativeBase]] Dict mapping fixture names to loaded instances
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.utils.load_fixtures_by_context","level":2,"title":"fastapi_toolsets.fixtures.utils.load_fixtures_by_context(session, registry, *contexts, strategy=LoadStrategy.MERGE) async","text":"Load all fixtures for specific contexts.
Parameters:
Name Type Description Defaultsession AsyncSession Database session
requiredregistry FixtureRegistry Fixture registry
required*contexts str | Context Contexts to load (e.g., Context.BASE, Context.TESTING)
() strategy LoadStrategy How to handle existing records
MERGE Returns:
Type Descriptiondict[str, list[DeclarativeBase]] Dict mapping fixture names to loaded instances
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/fixtures/#fastapi_toolsets.fixtures.utils.get_obj_by_attr","level":2,"title":"fastapi_toolsets.fixtures.utils.get_obj_by_attr(fixtures, attr_name, value)","text":"Get a SQLAlchemy model instance by matching an attribute value.
Parameters:
Name Type Description Defaultfixtures Callable[[], Sequence[ModelType]] A fixture function registered via @registry.register that returns a sequence of SQLAlchemy model instances.
attr_name str Name of the attribute to match against.
requiredvalue Any Value to match.
requiredReturns:
Type DescriptionModelType The first model instance where the attribute matches the given value.
Raises:
Type DescriptionStopIteration If no matching object is found in the fixture group.
","path":["Reference","fixtures"],"tags":[]},{"location":"reference/logger/","level":1,"title":"logger","text":"Here's the reference for the logging utilities.
You can import them directly from fastapi_toolsets.logger:
from fastapi_toolsets.logger import configure_logging, get_logger\n","path":["Reference","logger"],"tags":[]},{"location":"reference/logger/#fastapi_toolsets.logger.configure_logging","level":2,"title":"fastapi_toolsets.logger.configure_logging(level='INFO', fmt=DEFAULT_FORMAT, logger_name=None)","text":"Configure logging with a stdout handler and consistent format.
Sets up a :class:~logging.StreamHandler writing to stdout with the given format and level. Also configures the uvicorn loggers so that FastAPI access logs use the same format.
Calling this function multiple times is safe -- existing handlers are replaced rather than duplicated.
Parameters:
Name Type Description Defaultlevel LogLevel | int Log level (e.g. \"DEBUG\", \"INFO\", or logging.DEBUG).
'INFO' fmt str Log format string. Defaults to \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\".
DEFAULT_FORMAT logger_name str | None Logger name to configure. None (the default) configures the root logger so all loggers inherit the settings.
None Returns:
Type DescriptionLogger The configured Logger instance.
Examplefrom fastapi_toolsets.logger import configure_logging\n\nlogger = configure_logging(\"DEBUG\")\nlogger.info(\"Application started\")\n","path":["Reference","logger"],"tags":[]},{"location":"reference/logger/#fastapi_toolsets.logger.get_logger","level":2,"title":"fastapi_toolsets.logger.get_logger(name=_SENTINEL)","text":"Return a logger with the given name.
A thin convenience wrapper around :func:logging.getLogger that keeps logging imports consistent across the codebase.
When called without arguments, the caller's __name__ is used automatically, so get_logger() in a module is equivalent to logging.getLogger(__name__). Pass None explicitly to get the root logger.
Parameters:
Name Type Description Defaultname str | None Logger name. Defaults to the caller's __name__. Pass None to get the root logger.
_SENTINEL Returns:
Type DescriptionLogger A Logger instance.
Examplefrom fastapi_toolsets.logger import get_logger\n\nlogger = get_logger() # uses caller's __name__\nlogger = get_logger(\"myapp\") # explicit name\nlogger = get_logger(None) # root logger\n","path":["Reference","logger"],"tags":[]},{"location":"reference/metrics/","level":1,"title":"metrics","text":"Here's the reference for the Prometheus metrics registry and endpoint handler.
You can import them directly from fastapi_toolsets.metrics:
from fastapi_toolsets.metrics import Metric, MetricsRegistry, init_metrics\n","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.Metric","level":2,"title":"fastapi_toolsets.metrics.registry.Metric dataclass","text":"A metric definition with metadata.
","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.MetricsRegistry","level":2,"title":"fastapi_toolsets.metrics.registry.MetricsRegistry","text":"Registry for managing Prometheus metric providers and collectors.
","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.MetricsRegistry.get","level":3,"title":"get(name)","text":"Return the metric instance created by a provider.
Parameters:
Name Type Description Defaultname str The metric name (defaults to the provider function name).
requiredRaises:
Type DescriptionKeyError If the metric name is unknown or init_metrics has not been called yet.
get_all()","text":"Get all registered metric definitions.
","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.MetricsRegistry.get_collectors","level":3,"title":"get_collectors()","text":"Get collectors (called on each scrape).
","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.MetricsRegistry.get_providers","level":3,"title":"get_providers()","text":"Get metric providers (called once at init).
","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.MetricsRegistry.include_registry","level":3,"title":"include_registry(registry)","text":"Include another :class:MetricsRegistry into this one.
Parameters:
Name Type Description Defaultregistry MetricsRegistry The registry to merge in.
requiredRaises:
Type DescriptionValueError If a metric name already exists in the current registry.
","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.registry.MetricsRegistry.register","level":3,"title":"register(func=None, *, name=None, collect=False)","text":"Register a metric provider or collector function.
Can be used as a decorator with or without arguments.
Parameters:
Name Type Description Defaultfunc Callable[..., Any] | None The metric function to register.
None name str | None Metric name (defaults to function name).
None collect bool If True, the function is called on every scrape. If False (default), called once at init time.
False","path":["Reference","metrics"],"tags":[]},{"location":"reference/metrics/#fastapi_toolsets.metrics.handler.init_metrics","level":2,"title":"fastapi_toolsets.metrics.handler.init_metrics(app, registry, *, path='/metrics')","text":"Register a Prometheus /metrics endpoint on a FastAPI app.
Parameters:
Name Type Description Defaultapp FastAPI FastAPI application instance.
requiredregistry MetricsRegistry A :class:MetricsRegistry containing providers and collectors.
path str URL path for the metrics endpoint (default /metrics).
'/metrics' Returns:
Type DescriptionFastAPI The same FastAPI instance (for chaining).
Examplefrom fastapi import FastAPI\nfrom fastapi_toolsets.metrics import MetricsRegistry, init_metrics\n\nmetrics = MetricsRegistry()\napp = FastAPI()\ninit_metrics(app, registry=metrics)\n","path":["Reference","metrics"],"tags":[]},{"location":"reference/models/","level":1,"title":"models","text":"Here's the reference for the SQLAlchemy model mixins provided by the models module.
You can import them directly from fastapi_toolsets.models:
from fastapi_toolsets.models import (\n ModelEvent,\n UUIDMixin,\n UUIDv7Mixin,\n CreatedAtMixin,\n UpdatedAtMixin,\n TimestampMixin,\n WatchedFieldsMixin,\n watch,\n)\n","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.ModelEvent","level":2,"title":"fastapi_toolsets.models.ModelEvent","text":" Bases: str, Enum
Event types emitted by :class:WatchedFieldsMixin.
fastapi_toolsets.models.UUIDMixin","text":"Mixin that adds a UUID primary key auto-generated by the database.
","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.UUIDv7Mixin","level":2,"title":"fastapi_toolsets.models.UUIDv7Mixin","text":"Mixin that adds a UUIDv7 primary key auto-generated by the database.
","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.CreatedAtMixin","level":2,"title":"fastapi_toolsets.models.CreatedAtMixin","text":"Mixin that adds a created_at timestamp column.
fastapi_toolsets.models.UpdatedAtMixin","text":"Mixin that adds an updated_at timestamp column.
fastapi_toolsets.models.TimestampMixin","text":" Bases: CreatedAtMixin, UpdatedAtMixin
Mixin that combines created_at and updated_at timestamp columns.
fastapi_toolsets.models.WatchedFieldsMixin","text":"Mixin that enables lifecycle callbacks for SQLAlchemy models.
","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.WatchedFieldsMixin.on_create","level":3,"title":"on_create()","text":"Called after INSERT commit.
","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.WatchedFieldsMixin.on_delete","level":3,"title":"on_delete()","text":"Called after DELETE commit.
","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.WatchedFieldsMixin.on_event","level":3,"title":"on_event(event, changes=None)","text":"Catch-all callback fired for every lifecycle event.
Parameters:
Name Type Description Defaultevent ModelEvent The event type (:attr:ModelEvent.CREATE, :attr:ModelEvent.DELETE, or :attr:ModelEvent.UPDATE).
changes dict[str, dict[str, Any]] | None Field changes for :attr:ModelEvent.UPDATE, None otherwise.
None","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.WatchedFieldsMixin.on_update","level":3,"title":"on_update(changes)","text":"Called after UPDATE commit when watched fields change.
","path":["Reference","models"],"tags":[]},{"location":"reference/models/#fastapi_toolsets.models.watch","level":2,"title":"fastapi_toolsets.models.watch(*fields)","text":"Class decorator to filter which fields trigger on_update.
Parameters:
Name Type Description Default*fields str One or more field names to watch. At least one name is required.
() Raises:
Type DescriptionValueError If called with no field names.
","path":["Reference","models"],"tags":[]},{"location":"reference/pytest/","level":1,"title":"pytest","text":"Here's the reference for all testing utilities and pytest fixtures.
You can import them directly from fastapi_toolsets.pytest:
from fastapi_toolsets.pytest import (\n register_fixtures,\n create_async_client,\n create_db_session,\n worker_database_url,\n create_worker_database,\n cleanup_tables,\n)\n","path":["Reference","pytest"],"tags":[]},{"location":"reference/pytest/#fastapi_toolsets.pytest.plugin.register_fixtures","level":2,"title":"fastapi_toolsets.pytest.plugin.register_fixtures(registry, namespace, *, prefix='fixture_', session_fixture='db_session', strategy=LoadStrategy.MERGE)","text":"Register pytest fixtures from a FixtureRegistry.
Automatically creates pytest fixtures for each fixture in the registry. Dependencies are resolved via pytest fixture dependencies.
Parameters:
Name Type Description Defaultregistry FixtureRegistry The FixtureRegistry containing fixtures
requirednamespace dict[str, Any] The module's globals() dict to add fixtures to
requiredprefix str Prefix for generated fixture names (default: \"fixture_\")
'fixture_' session_fixture str Name of the db session fixture (default: \"db_session\")
'db_session' strategy LoadStrategy Loading strategy for fixtures (default: MERGE)
MERGE Returns:
Type Descriptionlist[str] List of created fixture names
Example# conftest.py\nfrom app.fixtures import fixtures\nfrom fastapi_toolsets.pytest_plugin import register_fixtures\n\nregister_fixtures(fixtures, globals())\n\n# Creates fixtures like:\n# - fixture_roles\n# - fixture_users (depends on fixture_roles if users depends on roles)\n# - fixture_posts (depends on fixture_users if posts depends on users)\n","path":["Reference","pytest"],"tags":[]},{"location":"reference/pytest/#fastapi_toolsets.pytest.utils.create_async_client","level":2,"title":"fastapi_toolsets.pytest.utils.create_async_client(app, base_url='http://test', dependency_overrides=None) async","text":"Create an async httpx client for testing FastAPI applications.
Parameters:
Name Type Description Defaultapp Any FastAPI application instance.
requiredbase_url str Base URL for requests. Defaults to \"http://test\".
'http://test' dependency_overrides dict[Callable[..., Any], Callable[..., Any]] | None Optional mapping of original dependencies to their test replacements. Applied via app.dependency_overrides before yielding and cleaned up after.
None Yields:
Type DescriptionAsyncGenerator[AsyncClient, None] An AsyncClient configured for the app.
Examplefrom fastapi import FastAPI\nfrom fastapi_toolsets.pytest import create_async_client\n\napp = FastAPI()\n\n@pytest.fixture\nasync def client():\n async with create_async_client(app) as c:\n yield c\n\nasync def test_endpoint(client: AsyncClient):\n response = await client.get(\"/health\")\n assert response.status_code == 200\n Example with dependency overrides from fastapi_toolsets.pytest import create_async_client, create_db_session\nfrom app.db import get_db\n\n@pytest.fixture\nasync def db_session():\n async with create_db_session(DATABASE_URL, Base, cleanup=True) as session:\n yield session\n\n@pytest.fixture\nasync def client(db_session):\n async def override():\n yield db_session\n\n async with create_async_client(\n app, dependency_overrides={get_db: override}\n ) as c:\n yield c\n","path":["Reference","pytest"],"tags":[]},{"location":"reference/pytest/#fastapi_toolsets.pytest.utils.create_db_session","level":2,"title":"fastapi_toolsets.pytest.utils.create_db_session(database_url, base, *, echo=False, expire_on_commit=False, drop_tables=True, cleanup=False) async","text":"Create a database session for testing.
Creates tables before yielding the session and optionally drops them after. Each call creates a fresh engine and session for test isolation.
Parameters:
Name Type Description Defaultdatabase_url str Database connection URL (e.g., \"postgresql+asyncpg://...\").
requiredbase type[DeclarativeBase] SQLAlchemy DeclarativeBase class containing model metadata.
requiredecho bool Enable SQLAlchemy query logging. Defaults to False.
False expire_on_commit bool Expire objects after commit. Defaults to False.
False drop_tables bool Drop tables after test. Defaults to True.
True cleanup bool Truncate all tables after test using :func:cleanup_tables. Defaults to False.
False Yields:
Type DescriptionAsyncGenerator[AsyncSession, None] An AsyncSession ready for database operations.
Examplefrom fastapi_toolsets.pytest import create_db_session\nfrom app.models import Base\n\nDATABASE_URL = \"postgresql+asyncpg://user:pass@localhost/test_db\"\n\n@pytest.fixture\nasync def db_session():\n async with create_db_session(\n DATABASE_URL, Base, cleanup=True\n ) as session:\n yield session\n\nasync def test_create_user(db_session: AsyncSession):\n user = User(name=\"test\")\n db_session.add(user)\n await db_session.commit()\n","path":["Reference","pytest"],"tags":[]},{"location":"reference/pytest/#fastapi_toolsets.pytest.utils.worker_database_url","level":2,"title":"fastapi_toolsets.pytest.utils.worker_database_url(database_url, default_test_db)","text":"Derive a per-worker database URL for pytest-xdist parallel runs.
Appends _{worker_name} to the database name so each xdist worker operates on its own database. When not running under xdist, _{default_test_db} is appended instead.
The worker name is read from the PYTEST_XDIST_WORKER environment variable (set automatically by xdist in each worker process).
Parameters:
Name Type Description Defaultdatabase_url str Original database connection URL.
requireddefault_test_db str Suffix appended to the database name when PYTEST_XDIST_WORKER is not set.
Returns:
Type Descriptionstr A database URL with a worker- or default-specific database name.
","path":["Reference","pytest"],"tags":[]},{"location":"reference/pytest/#fastapi_toolsets.pytest.utils.create_worker_database","level":2,"title":"fastapi_toolsets.pytest.utils.create_worker_database(database_url, default_test_db='test_db') async","text":"Create and drop a per-worker database for pytest-xdist isolation.
Derives a worker-specific database URL using :func:worker_database_url, then delegates to :func:~fastapi_toolsets.db.create_database to create and drop it. Intended for use as a session-scoped fixture.
When running under xdist the database name is suffixed with the worker name (e.g. _gw0). Otherwise it is suffixed with default_test_db.
Parameters:
Name Type Description Defaultdatabase_url str Original database connection URL (used as the server connection and as the base for the worker database name).
requireddefault_test_db str Suffix appended to the database name when PYTEST_XDIST_WORKER is not set. Defaults to \"test_db\".
'test_db' Yields:
Type DescriptionAsyncGenerator[str, None] The worker-specific database URL.
Examplefrom fastapi_toolsets.pytest import create_worker_database, create_db_session\n\nDATABASE_URL = \"postgresql+asyncpg://postgres:postgres@localhost/test_db\"\n\n@pytest.fixture(scope=\"session\")\nasync def worker_db_url():\n async with create_worker_database(DATABASE_URL) as url:\n yield url\n\n@pytest.fixture\nasync def db_session(worker_db_url):\n async with create_db_session(\n worker_db_url, Base, cleanup=True\n ) as session:\n yield session\n","path":["Reference","pytest"],"tags":[]},{"location":"reference/schemas/","level":1,"title":"schemas","text":"Here's the reference for all response models and types provided by the schemas module.
You can import them directly from fastapi_toolsets.schemas:
from fastapi_toolsets.schemas import (\n PydanticBase,\n ResponseStatus,\n ApiError,\n BaseResponse,\n Response,\n ErrorResponse,\n OffsetPagination,\n CursorPagination,\n PaginationType,\n PaginatedResponse,\n OffsetPaginatedResponse,\n CursorPaginatedResponse,\n)\n","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.PydanticBase","level":2,"title":"fastapi_toolsets.schemas.PydanticBase","text":" Bases: BaseModel
Base class for all Pydantic models with common configuration.
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.ResponseStatus","level":2,"title":"fastapi_toolsets.schemas.ResponseStatus","text":" Bases: str, Enum
Standard API response status.
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.ApiError","level":2,"title":"fastapi_toolsets.schemas.ApiError","text":" Bases: PydanticBase
Structured API error definition.
Used to define standard error responses with consistent format.
Attributes:
Name Type Descriptioncode int HTTP status code
msg str Short error message
desc str Detailed error description
err_code str Application-specific error code (e.g., \"AUTH-401\")
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.BaseResponse","level":2,"title":"fastapi_toolsets.schemas.BaseResponse","text":" Bases: PydanticBase
Base response structure for all API responses.
Attributes:
Name Type Descriptionstatus ResponseStatus SUCCESS or FAIL
message str Human-readable message
error_code str | None Error code if status is FAIL, None otherwise
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.Response","level":2,"title":"fastapi_toolsets.schemas.Response","text":" Bases: BaseResponse, Generic[DataT]
Generic API response with data payload.
ExampleResponse[UserRead](data=user, message=\"User retrieved\")\n","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.ErrorResponse","level":2,"title":"fastapi_toolsets.schemas.ErrorResponse","text":" Bases: BaseResponse
Error response with additional description field.
Used for error responses that need more context.
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.OffsetPagination","level":2,"title":"fastapi_toolsets.schemas.OffsetPagination","text":" Bases: PydanticBase
Pagination metadata for offset-based list responses.
Attributes:
Name Type Descriptiontotal_count int | None Total number of items across all pages. None when include_total=False.
items_per_page int Number of items per page
page int Current page number (1-indexed)
has_more bool Whether there are more pages
pages int | None Total number of pages
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.OffsetPagination.pages","level":3,"title":"pages property","text":"Total number of pages, or None when total_count is unknown.
fastapi_toolsets.schemas.CursorPagination","text":" Bases: PydanticBase
Pagination metadata for cursor-based list responses.
Attributes:
Name Type Descriptionnext_cursor str | None Encoded cursor for the next page, or None on the last page.
prev_cursor str | None Encoded cursor for the previous page, or None on the first page.
items_per_page int Number of items requested per page.
has_more bool Whether there is at least one more page after this one.
","path":["Reference","schemas"],"tags":[]},{"location":"reference/schemas/#fastapi_toolsets.schemas.PaginationType","level":2,"title":"fastapi_toolsets.schemas.PaginationType","text":" Bases: str, Enum
Pagination strategy selector for :meth:.AsyncCrud.paginate.
fastapi_toolsets.schemas.PaginatedResponse","text":" Bases: BaseResponse, Generic[DataT]
Paginated API response for list endpoints.
Base class and return type for endpoints that support both pagination strategies. Use :class:OffsetPaginatedResponse or :class:CursorPaginatedResponse when the strategy is fixed.
When used as PaginatedResponse[T] in a return annotation, subscripting returns Annotated[Union[CursorPaginatedResponse[T], OffsetPaginatedResponse[T]], Field(discriminator=\"pagination_type\")] so FastAPI emits a proper oneOf + discriminator in the OpenAPI schema.
fastapi_toolsets.schemas.OffsetPaginatedResponse","text":" Bases: PaginatedResponse[DataT]
Paginated response with typed offset-based pagination metadata.
The pagination_type field is always \"offset\" and acts as a discriminator, allowing frontend clients to narrow the union type returned by a unified paginate() endpoint.
fastapi_toolsets.schemas.CursorPaginatedResponse","text":" Bases: PaginatedResponse[DataT]
Paginated response with typed cursor-based pagination metadata.
The pagination_type field is always \"cursor\" and acts as a discriminator, allowing frontend clients to narrow the union type returned by a unified paginate() endpoint.