Skip to content

API Reference

CRUDCollection

CRUDCollection

Bases: CRUDCollectionBase

Concrete CRUD collection — subclass and set orm_adapter to use.

__init__(orm_adapter=None, public_schema=None, public_list_schema=None, update_schema=None, update_out_schema=None, create_schema=None, create_out_schema=None, base_fields=None, public_fields=None, create_fields=None, update_fields=None, filter_schema=None, sort_schema=None, include_schema=None, pk_fields=None, dependencies=None, get_one_dependencies=None, get_many_dependencies=None, create_dependencies=None, update_dependencies=None, delete_dependencies=None, disable_get_one=None, disable_get_many=None, disable_create=None, disable_update=None, disable_delete=None, dependency_overrides=None, **router_kwargs)

Initialise the collection, resolving schemas and dependencies.

apply_pk_aliases(pk_schema)

Return pk_schema with model-name-prefixed aliases on plain fields.

Fields whose names contain no underscore get an alias {model_name}_{field} (e.g. iduser_id). Override to customise aliasing behaviour.

verify_orm_adapter()

Raise if orm_adapter is not set.

get_resolved_overrides(strategy=None)

Merge default overrides with user-supplied dependency_overrides.

override_dependencies(original_func, overrides=None)

Replace marker annotations in a handler's signature with real DI.

get_one_handler(pk_field_values, include_data, parent_refs) async

Return a single object or call get_one_not_found if missing.

get_one_not_found(_pk_field_values, _include_data) async

Raise 404 by default; override to customise not-found behavior.

get_many_handler(paginator, filter_data, sort_data, include_data, parent_refs) async

Handle GET / — return a paginated, filtered, sorted list.

create_one_handler(create_data, parent_refs) async

Handle POST / — persist a new object and return it.

update_one_handler(pk_field_values, update_data, parent_refs) async

Handle PATCH /{pk} — partially update an existing object.

delete_one_handler(pk_field_values, parent_refs) async

Handle DELETE /{pk} — delete an object by primary key.

generate_unique_id(route)

Build a unique OpenAPI operation ID from name, path and method.

get_id_path(exclude=frozenset())

URL path segment for single-object endpoints, e.g. /{user_id}.

exclude drops pk params already bound by an ancestor's path, so a nested collection does not repeat them. Override this to pin a fixed segment (e.g. return "/me" for a token-scoped singleton, where the identity comes from auth, not the URL).

add_get_many_route(router, strategy=None)

Register GET / on the router.

add_get_one_route(router, strategy=None)

Register GET /{pk} on the router.

add_create_one_route(router, strategy=None)

Register POST / on the router.

add_update_one_route(router, strategy=None)

Register PATCH /{pk} on the router.

add_delete_one_route(router, strategy=None)

Register DELETE /{pk} on the router.

add_nested_collection(path, child, config=None)

Register child as a nested collection under this collection.

get_router(strategy=None, **router_kwargs)

Build and return an APIRouter with all enabled CRUD routes.

CRUDCollectionBase

Bases: ABC

Base class for CRUD route collections.

Subclass this (or CRUDCollection) to create a set of CRUD endpoints for a given ORM adapter. Override handler methods or class attributes to customise behaviour without touching routing or dependency wiring.

__init__(orm_adapter=None, public_schema=None, public_list_schema=None, update_schema=None, update_out_schema=None, create_schema=None, create_out_schema=None, base_fields=None, public_fields=None, create_fields=None, update_fields=None, filter_schema=None, sort_schema=None, include_schema=None, pk_fields=None, dependencies=None, get_one_dependencies=None, get_many_dependencies=None, create_dependencies=None, update_dependencies=None, delete_dependencies=None, disable_get_one=None, disable_get_many=None, disable_create=None, disable_update=None, disable_delete=None, dependency_overrides=None, **router_kwargs)

Initialise the collection, resolving schemas and dependencies.

apply_pk_aliases(pk_schema)

Return pk_schema with model-name-prefixed aliases on plain fields.

Fields whose names contain no underscore get an alias {model_name}_{field} (e.g. iduser_id). Override to customise aliasing behaviour.

verify_orm_adapter()

Raise if orm_adapter is not set.

get_resolved_overrides(strategy=None)

Merge default overrides with user-supplied dependency_overrides.

override_dependencies(original_func, overrides=None)

Replace marker annotations in a handler's signature with real DI.

get_one_handler(pk_field_values, include_data, parent_refs) async

Return a single object or call get_one_not_found if missing.

get_one_not_found(_pk_field_values, _include_data) async

Raise 404 by default; override to customise not-found behavior.

get_many_handler(paginator, filter_data, sort_data, include_data, parent_refs) async

Handle GET / — return a paginated, filtered, sorted list.

create_one_handler(create_data, parent_refs) async

Handle POST / — persist a new object and return it.

update_one_handler(pk_field_values, update_data, parent_refs) async

Handle PATCH /{pk} — partially update an existing object.

delete_one_handler(pk_field_values, parent_refs) async

Handle DELETE /{pk} — delete an object by primary key.

generate_unique_id(route)

Build a unique OpenAPI operation ID from name, path and method.

get_id_path(exclude=frozenset())

URL path segment for single-object endpoints, e.g. /{user_id}.

exclude drops pk params already bound by an ancestor's path, so a nested collection does not repeat them. Override this to pin a fixed segment (e.g. return "/me" for a token-scoped singleton, where the identity comes from auth, not the URL).

add_get_many_route(router, strategy=None)

Register GET / on the router.

add_get_one_route(router, strategy=None)

Register GET /{pk} on the router.

add_create_one_route(router, strategy=None)

Register POST / on the router.

add_update_one_route(router, strategy=None)

Register PATCH /{pk} on the router.

add_delete_one_route(router, strategy=None)

Register DELETE /{pk} on the router.

add_nested_collection(path, child, config=None)

Register child as a nested collection under this collection.

get_router(strategy=None, **router_kwargs)

Build and return an APIRouter with all enabled CRUD routes.

Adapters

SQLModelAdapter

Bases: ORMAdapterBase

ORM adapter for SQLModel with async SQLAlchemy sessions.

Implements schema generation by introspecting SQLModel metadata: primary keys via __table__.primary_key, server-generated fields via server_default, and output-only fields via exclude=True. ORM-specific FieldInfoMetadata is stripped from all generated schemas so the resulting Pydantic models are clean of SQLAlchemy internals.

Parameters:

Name Type Description Default
get_session Callable[[], AsyncGenerator[AsyncSession, None, None]]

Async generator that yields an AsyncSession.

None
model type[SQLModel] | None

The SQLModel table class to operate on.

None

get_server_generated_field_names()

Return field names backed by a column with server_default.

get_default_public_fields()

Return all model field names that are not explicitly excluded.

get_default_create_fields(exclude_related=None)

Return field names except auto-generated PKs and server fields.

A PK field is excluded when it has no default (auto-increment/uuid4) or when it is a FK pointing to a model in exclude_related — meaning its value comes from the parent URL, not the request body.

generate_flat_public_schema(fields=None, base_fields=None)

Build a schema from model fields only, without relationships.

get_default_update_fields()

Return field names except all PKs and server-generated fields.

Unlike create, ALL PK fields are excluded — they come from the URL path and must never be changed via the request body.

generate_pk_schema()

Build a Pydantic model containing only the primary key fields.

generate_include_schema()

Build a query schema for selecting which relationships to include.

Creates a Pydantic model with an include field typed as Literal[<relationship names>], so FastAPI validates that only existing relationship names are accepted as query parameters.

get_base_list_queryset(parent_refs=None)

Build the base SELECT for list ops, scoped to parent.

get_base_single_queryset(parent_refs=None)

Build the base SELECT for single-record ops, scoped to parent.

get_one(pk_values, include_data, parent_refs=None) async

Return a single object by primary key, or None if not found.

get_many(filter_data, sort_data, include_data, paginator, parent_refs=None) async

Return a paginated, filtered, sorted list.

create_one(data, parent_refs=None) async

Persist a new object, verifying the parent chain first.

update_one(pk_values, data, parent_refs=None) async

Update an existing object by primary key, scoped to parent chain.

delete_one(pk_values, parent_refs=None) async

Delete an object by primary key, scoped to parent chain.

SQLAlchemyAdapter

Bases: ORMAdapterBase

ORM adapter for SQLAlchemy async (DeclarativeBase) models.

Works with any model that inherits from SQLAlchemy's DeclarativeBase. Schemas are generated by introspecting the SA mapper — no Pydantic annotations required on the model.

Parameters:

Name Type Description Default
get_session Callable[[], AsyncGenerator[AsyncSession, None]]

Async generator yielding an AsyncSession.

None
model type | None

The declarative ORM model class to operate on.

None

TortoiseAdapter

Bases: ORMAdapterBase

ORM adapter for Tortoise ORM models.

Tortoise uses a global connection pool (Tortoise.init), so unlike SQLAlchemy-based adapters there is no get_session factory. Pass the Tortoise model class directly.

Composite primary keys are not supported by Tortoise; this adapter assumes a single pk field per model.

Parameters:

Name Type Description Default
model type | None

The Tortoise ORM model class.

None

ORMAdapterBase

Bases: ABC

Abstract base class for ORM adapters.

An adapter bridges a specific ORM and CRUDCollection by implementing schema generation and pure data-access methods. Each ORM has its own adapter subclass (e.g. SQLModelAdapter) that translates the generic interface into ORM-specific queries and schema introspection.

HTTP concerns (routing, status codes, dependency injection) live in CRUDCollection, not here.

generate_public_schema(fields=None, base_fields=None) abstractmethod

Build a Pydantic model for API read responses.

Fields are resolved in priority order:

  1. fields argument (main) + base_fields — unioned together.
  2. crud_config.public_fields (main) + crud_config.base_fields — used when the corresponding explicit argument is omitted.
  3. Adapter default — all non-excluded fields plus the primary key. Applied only when both main and base resolve to nothing. If only base_fields is set, the result is base_fields alone; the default is skipped.

Parameters:

Name Type Description Default
fields set[str] | None

Main field set. Overrides crud_config.public_fields and adapter defaults.

None
base_fields set[str] | None

Extra fields unioned with the main set. Overrides crud_config.base_fields when provided.

None

Returns:

Type Description
type[BaseModel]

A Pydantic model class containing only the resolved fields.

generate_create_schema(fields=None, base_fields=None, exclude_related=None) abstractmethod

Build a Pydantic model for object creation payloads.

Fields are resolved in priority order:

  1. fields argument (main) + base_fields — unioned together.
  2. crud_config.create_fields (main) + crud_config.base_fields — used when the corresponding explicit argument is omitted.
  3. Adapter default — all fields except primary keys and fields whose values are generated by the database (e.g. server_default). Applied only when both main and base resolve to nothing. If only base_fields is set, the result is base_fields alone; the default is skipped.

Note: fields marked exclude=True are not excluded here — that marker controls serialization of responses, not input acceptance.

Parameters:

Name Type Description Default
fields set[str] | None

Main field set. Overrides crud_config.create_fields and adapter defaults.

None
base_fields set[str] | None

Extra fields unioned with the main set. Overrides crud_config.base_fields when provided.

None

Returns:

Type Description
type[BaseModel]

A Pydantic model class containing only the resolved fields.

generate_update_schema(fields=None, base_fields=None) abstractmethod

Build a Pydantic model for partial update (PATCH) payloads.

Uses the same field resolution logic as generate_create_schema, but every field is made optional so clients only send what they want to change.

Parameters:

Name Type Description Default
fields set[str] | None

Main field set. Overrides crud_config.update_fields and adapter defaults.

None
base_fields set[str] | None

Extra fields unioned with the main set. Overrides crud_config.base_fields when provided.

None

Returns:

Type Description
type[BaseModel]

A Pydantic model class where every field is optional.

get_model_name()

Return the lowercase model name, or empty string if unavailable.

generate_pk_schema() abstractmethod

Build a Pydantic model containing only the primary key fields.

generate_include_schema() abstractmethod

Build a query schema for selecting which relationships to include.

The returned model should have an include field that accepts a list of valid relationship names. FastAPI uses it to validate that only existing relationships are requested as query parameters.

get_one(pk_values, include_data, parent_refs=None) abstractmethod async

Return a single object by primary key, or None if not found.

get_many(filter_data, sort_data, include_data, paginator, parent_refs=None) abstractmethod async

Return a paginated, filtered, sorted list.

create_one(data, parent_refs=None) abstractmethod async

Persist a new object and return it.

update_one(pk_values, data, parent_refs=None) abstractmethod async

Update an existing object by primary key.

delete_one(pk_values, parent_refs=None) abstractmethod async

Delete an object by primary key and return it, or None.

Configuration

CRUDConfigDict dataclass

Configuration for automatic CRUD schema generation.

Place on a SQLModel table class as crud_config to control how the ORM adapter generates schemas and routes.

Attributes:

Name Type Description
base_fields set[str]

Fields shared across schemas; used as a fallback when public_fields, create_fields or update_fields are not set.

public_fields set[str]

Fields exposed in the public (GET) schema.

create_fields set[str]

Fields accepted in the create (POST) schema.

update_fields set[str]

Fields accepted in the update (PATCH) schema.

NestedConfig dataclass

Configuration for a nested collection.

Passed as config to add_nested_collection.

router_kwargs accepts any APIRouter.include_router parameters (tags, dependencies, deprecated, include_in_schema, responses).

Pagination

PaginatorBase

Bases: ABC

Base class for paginators injected as FastAPI dependencies.

Subclass and implement paginate to provide ORM-specific query execution. page and per_page are read from query parameters automatically.

set_page(page)

Set current page and recalculate limit/offset.

set_per_page(per_page)

Set page size and recalculate limit/offset.

calc_offset_limit()

Recalculate limit and offset from current page and per_page.

paginate() abstractmethod async

Execute the query and return a paginated result page.

PaginatorPage

Bases: BaseModel, Generic[ListItemT]

Schemas & Errors

ParentRef dataclass

Bases: Generic[ModelT]

Reference to a parent collection item in a nested route.

Passed to ORM adapter methods so they can filter, set foreign keys, or verify ownership relative to the parent object.

Attributes:

Name Type Description
model type[ModelT]

The parent's ORM model class (e.g. User).

pk_values BaseModel

The parent's primary key values parsed from the URL.

NotFoundError

Bases: Exception

Raised by ORM adapters when a requested resource does not exist.

ParentNotFoundError

Bases: NotFoundError

Raised when a parent resource does not exist or is not accessible.