Views API#

fastapi_restly.views implements the class-based view layer. RestView and AsyncRestView define CRUD endpoint methods for a model. View is the bare primitive for hand-written endpoint groups. include_view() registers either on a FastAPI app.

Class-based views with default CRUD methods.

Every CRUD route on RestView / AsyncRestView runs through three methods. The handler handles the steps, and you override a step:

  1. <verb>_endpoint, the endpoint method: the @route, FastAPI signature and response_model. Replace only to change the HTTP contract.

  2. handle_<verb>, the handler: handles the steps, authorize, the load or the business method, and the commit bracket (before_action_commit -> commit -> after_action_commit). Call it from a custom route. You cannot override it.

  3. create, update, delete, the business method: the domain operation, auth-free and commit-free. The usual override point. It changes objects in the session and returns the object; it does not flush.

get_one and get_many are the loads. You cannot override them. They start from select(): the scope and the loader options.

Cross-cutting seams: scope (read visibility), where_id (the row an id names), not_found (the error for a missing row), get_loader_options (what a read loads), authorize (policy), apply_list_params (list params), to_single_response and to_list_response (the response), write_action (custom write actions), shared_write_action_commit (one commit over several writes). After a write business method, the commit bracket saves: it adds a new object, flushes, refreshes the object and every other row of the view’s model that the action wrote, and loads them with the loader options. fr.objects has the schema-to-ORM functions, for another model and for code outside a view; a server-stamped field is a column default on the model. View is the bare class-based primitive for non-CRUD endpoint groups (auth flows, webhooks, RPC).

class fastapi_restly.views.RestView#

Bases: BaseRestView[ModelT, ResponseSchemaT, CreateSchemaT, UpdateSchemaT, IdT]

RestView creates a sync CRUD/REST interface for database objects. Basic usage:

class FooView(RestView):
    prefix = "/foo"
    schema = FooSchema
    model = Foo

Each CRUD route runs through three methods (see “CRUD Routes” in the docs):

  • <verb>_endpoint: the endpoint method. Owns the HTTP signature, and response_model. Override it to change the HTTP contract.

  • handle_<verb>: the handler. Handles the steps: authorize, the load or the business method, and the commit bracket (before_action_commit -> commit -> after_action_commit); returns the domain object. Call it from a custom route to run the same steps. You cannot override it.

  • create / update / delete: the business method. Auth-free, commit-free; the common override point (hash a password, …). It changes objects in the session and does not flush: the commit bracket saves.

get_one and get_many are the loads. As with the handlers, you cannot override them. They start from select(): the scope and the loader options. Change a load through scope, where_id, not_found, apply_list_params and get_loader_options.

session: SessionDep#

The SQLAlchemy Session of this request, from fr.SessionDep. To use another database on one view, give the attribute another annotation; see Use another database on one view.

get_many_endpoint(list_params: Any) → ViewListResponse#

GET / endpoint method. Put the rows in scope, and the list params in apply_list_params. Restly builds the response with to_list_response. Replace this method only to change the HTTP contract.

get_one_endpoint(id: IDType) → ViewResponse#

GET /{id} endpoint method. Put the rows in scope, and the lookup of the id in where_id. Restly builds the response with to_single_response. Replace this method only to change the HTTP contract.

create_endpoint(data: ViewCreate) → ViewResponse#

POST / endpoint method. Override create for domain logic (it is commit-free; the handler owns the commit). Restly builds the response with to_single_response. Replace this method only to change the HTTP contract.

update_endpoint(id: IDType, data: ViewUpdate) → ViewResponse#

PATCH /{id} endpoint method. Override update for domain logic. Restly builds the response with to_single_response. Replace this method only to change the HTTP contract.

delete_endpoint(id: IDType) → None#

DELETE /{id} endpoint method. Override delete for domain logic (e.g. soft delete); replace this method only to change the HTTP contract (e.g. return the deleted object instead of 204).

handle_get_many(list_params: Any, *, scope: WhereClause | None = None, where: ColumnElement[bool] | WhereClause | None = None) → ListResult[ModelT]#

List handler: authorize, then the get_many load.

You cannot override it, as with every handler: authorize is the gate, and the list params and the scope decide the rows. Call it from a custom list route.

Parameters:
  • scope – a clause that replaces the view scope for this read, so a custom route can list another surface of the same model (a trash list); fr.clauses.UNSCOPED reads past it. Forwarded to get_many.

  • where – a SQLAlchemy boolean expression or a clause that narrows this read inside the scope, so a nested list keeps the visibility rules (where=Task.project_id == id). The page and total_count both apply it. Forwarded to get_many.

Raises:

TypeError – where is a Python bool (a comparison on a loaded object), or neither an expression nor a clause.

handle_get_one(id: IdT | ColumnElement[bool], *, scope: WhereClause | None = None) → ModelT#

Retrieve handler: scoped load (404 by visibility) then read-auth.

You cannot override it: authorize is the gate, and where_id and not_found shape the load. Call it from a custom read route as “load with scope + 404 + read-auth”. A write action instead loads with get_one(id, scope=...) and gates only its own action, the way handle_update and handle_delete do.

Parameters:
  • id – the id from the path, which where_id turns into the WHERE, or a SQLAlchemy boolean expression that picks the row instead, so a natural-key route is this handler with Item.slug == slug. Forwarded to get_one.

  • scope – a clause that replaces the view scope for this read, so a restore route can load the row the view scope hides. Forwarded to get_one.

write_action(action: str, *, obj: Any, data: Any = None) → AbstractContextManager[None]#

Run one write action of a custom route: authorize, the reference check, your change, the save and the commit.

obj is the row that the action is about. It is required:

  • A row from the database, such as one from get_one. The block changes it. authorize gets the row, and old is its snapshot:

    with self.write_action(self.Action.PUBLISH, obj=post):
        post.published = True
    
  • A new object that is not in the database yet: the action creates it. Restly adds it to the session when the block starts, so a flush in the block gives it an id. authorize gets obj=None, as on POST /, and old is None. Pass the request as data, so that authorize sees what the action creates. Do not session.add() the object before the block, and do not append it to a collection of a loaded row there: the block begins with a flush, so an error in the block would not undo that row:

    upload = Upload(filename=file.filename)
    with self.write_action(self.Action.CREATE, obj=upload, data=form):
        self.session.flush()  # upload.id, for the lines
        self.session.add_all(UploadLine(upload_id=upload.id) ...)
    
  • None: the action has no single row, such as a change to several rows. authorize gets obj=None, and the hooks get new=None and old=None.

action is the name that authorize and the hooks get. It is one of the names that the view’s Action class declares, such as self.Action.PUBLISH. data goes to authorize, and Restly checks the references in it, as a CRUD write does: the MustExist, IDRef and IDSchema fields, also in nested schemas and in each item of a list. A missing row raises NotFound (404).

The block runs under session.no_autoflush: nothing is written until the block ends, and a query in the block does not see your unflushed changes. When the block ends, Restly flushes the session. Then it refreshes obj and every other row of the view’s model that the action wrote, and loads them with get_loader_options(), so the route can return them. When the block deleted obj, as a merge deletes its source, new is None. Then Restly runs before_action_commit(action, new, old), commits, and runs after_action_commit(action, new, old). The block gets nothing from as. Code after the block runs after the commit, but not when the block runs inside another block: then it runs before the commit. Work that needs the commit goes in after_action_commit.

An exception in the block skips the save and the commit. The outermost block runs in a savepoint, and Restly rolls back to it, so what the block changed is undone. The outermost block on the session owns the commit and the after-hooks. So a handler or a write_action inside this block, or this block inside shared_write_action_commit(), returns after its save and before_action_commit. Its save also writes the changes of this block so far, so set the required values of the block’s objects before you call it. An IntegrityError from authorize to the commit becomes Conflict (409) when it leaves the outermost block, and stays raw inside it. A direct session.commit() inside the block raises RuntimeError. When the outermost block is a write action of a view with atomic_write_actions = False, code in the block may commit, and there is no savepoint: an error rolls back all that is not committed.

Raises:
  • ValueError – the view’s Action does not declare action.

  • TypeError – obj is neither None nor an object of a SQLAlchemy model.

shared_write_action_commit() → AbstractContextManager[None]#

Share one commit across write actions on this session.

The outermost block commits once, then runs the queued after_action_commit hooks. write_action and the write handlers still authorize, check the references, change, save, and run before_action_commit. They return uncommitted objects inside the block:

with self.shared_write_action_commit():
    for item in items:
        self.handle_create(item)

Serialize returned objects and run code that depends on an after-hook only after the block exits. Nested blocks on the same session share the commit. An exception escaping a deferred-commit block aborts the shared commit, including when an enclosing deferred-commit block catches that exception. A write action that raises after it changed objects stops the commit too, unless the rollback of a savepoint around it undid the change: run each write that a route may refuse in session.begin_nested(). The outermost block runs in a savepoint of its own. When an exception leaves it, Restly rolls back to that savepoint: the changes of the block are undone, and the session can write again. An IntegrityError inside the block stays raw, so a route can catch the error of one row; one that escapes the outermost block, or that its commit raises, becomes Conflict (409).

After-hooks run in queue order and stop on the first exception. new is the live object after all writes, while old is each action’s snapshot. Direct session.commit() calls raise RuntimeError, unless the block is inside a write action of a view with atomic_write_actions = False. An async write action needs an async outermost block; a sync one joins either.

handle_create(data: CreateSchemaT) → ModelT#

Create handler: authorize, the reference check, create, commit bracket.

You cannot override it. Override create for the domain change, authorize for the gate, and before_action_commit / after_action_commit for side effects. authorize gets the payload, and no row. The object that create returns is the subject of the action: the save adds it, flushes, refreshes it, and the hooks get it as new. Call this from a custom create route, and from inside shared_write_action_commit() to share one commit with other writes; it then returns after the save, before the commit.

Raises:

TypeError – create returned None.

handle_update(id: IdT | ColumnElement[bool], data: UpdateSchemaT) → ModelT#

Update handler: scoped load, then update in the commit bracket.

You cannot override it, as with handle_create(): update receives the loaded object, so the load, the 404, authorize and the reference check stay here. old is the snapshot of the loaded row, and new is the object that update returns, after the save. Inside shared_write_action_commit() it returns before the commit.

Raises:

TypeError – update returned None.

handle_delete(id: IdT | ColumnElement[bool]) → None#

Delete handler: scoped load, then delete in the commit bracket.

You cannot override it, as with handle_create(). The loaded row is the subject. After a hard delete, the hooks get new=None. A soft delete flips a timestamp in delete and keeps the row, so the hooks get the row as new. An off-request follow-up runs in after_action_commit. Inside shared_write_action_commit(), the change runs at once, and the after-hook waits for the outermost block to commit.

get_many(list_params: Any, *, scope: WhereClause | None = None, where: ColumnElement[bool] | WhereClause | None = None) → ListResult[ModelT]#

The load of the list: the rows the scope allows, filtered and paged by list_params.

You cannot override it. It is auth-free: handle_get_many adds authorize. The statement is select(), then apply_list_params(). A paginated view also runs count() for total_count; a view without pagination returns every matching row with total_count=None. Override apply_list_params to filter, sort or page in another way, and to_single_response to add a value to each row.

Parameters:
  • list_params – the list params (filter, sort, page) as the endpoint receives them. A QueryParams or a mapping goes through list_params_schema first, as on the list route.

  • scope – a clause that replaces the view scope for this read; fr.clauses.UNSCOPED reads unscoped.

  • where – a SQLAlchemy boolean expression or a clause that narrows this read inside the scope.

Raises:

TypeError – where is a Python bool (a comparison on a loaded object), or neither an expression nor a clause.

get_one(id: IdT | ColumnElement[bool], *, scope: WhereClause | None = None) → ModelT#

The load of one row: the row id names, through the scope, or the exception of not_found().

You cannot override it. It is auth-free: handle_get_one adds authorize; a write action calls this directly and gates its own action. The statement is select() with where_id(), so a row outside the scope is a 404 for every caller. Override where_id to find the row by another key, and not_found to change the 404.

Parameters:
  • id – the id from the path, or a SQLAlchemy boolean expression that picks the row instead (get_one(Item.slug == slug)). An expression narrows inside the scope; only scope= replaces it.

  • scope – a clause that replaces the view scope for this read; fr.clauses.UNSCOPED reads unscoped.

Raises:
  • fastapi_restly.exc.NotFound – no row matches inside the scope, or the exception that not_found returns.

  • sqlalchemy.exc.MultipleResultsFound – more than one row matches; an ambiguous key is a bug in the criterion.

  • TypeError – id is a Python bool (a comparison on a loaded object, which would render as WHERE true), an uncalled clause (a scope, not a row identity), or an expression on a table that the query does not select from; or where_id or not_found returned a value of the wrong kind.

create(data: CreateSchemaT) → ModelT#

Build a new object from data and return it.

Auth-free, flush-free and commit-free: handle_create checks the references before this method, and saves and commits after it. The default is fr.objects.make_new_object with the view’s model: it adds the object to the session, without a flush, so the object has no id yet. Override to change the object before the save (hash a password from the request): call super().create(), change the object, and return it.

Nothing is written until the save after this method: the handler runs it under session.no_autoflush, so a query here does not flush the new object, and it does not see your unflushed changes. Call self.session.flush() when you need the id inside this method. A direct call, outside handle_create, writes nothing.

update(obj: ModelT, data: UpdateSchemaT) → ModelT#

Apply data to the loaded obj and return it.

Auth-free, flush-free and commit-free: handle_update loads obj through get_one, gates, checks the references, and saves and commits after this method. The default is fr.objects.update_object. Override to check the stored row first, or to change the object after super().update(). As in create, nothing is written before the save, and a direct call writes nothing.

delete(obj: ModelT) → None#

Mark obj for deletion. Does not flush or commit: handle_delete does.

Override (on the view or on a soft-delete mixin) to flip a timestamp instead of removing the row, without calling super(). A raw row delete elsewhere is fr.objects.delete_object(self.session, obj).

apply_list_params(stmt: Select, list_params: Any) → Select#

Apply the list params to stmt: apply_filters(), then the sort, then the page.

Override for list params of your own; the common case is driven by configuration. A QueryParams or a mapping goes through list_params_schema first, as on the list route. In a QueryParams, a key that the route reads is left out. Any other key that the list params do not have raises RequestValidationError, as on the list route (see unknown_query_params).

apply_filters(stmt: Select, list_params: Any) → Select#

Apply the filters of list_params to stmt, without the sort and the page.

For a route that reads the client’s filters but has its own order or no rows to page, such as a count per category with GROUP BY. Like every custom read route, such a route calls authorize() and starts from select(), which applies the scope. apply_list_params() calls this method first. A QueryParams or a mapping goes through list_params_schema first, as on the list route. In a QueryParams, a key that the route reads is left out. Any other key that the list params do not have raises RequestValidationError, as on the list route (see unknown_query_params).

The generated filters come first, then the view’s own filters from list_filter(), in the order of the class.

count(stmt: Select) → int#

Total for the list, ignoring presentation-layer ordering/pagination.

It counts the distinct primary keys of the model that stmt selects, without its order and page. So a join to a to-many relationship does not count a row twice. No other column is part of the count, so a json column works on PostgreSQL, and the subquery of a column_property does not run for every row. A stmt that selects columns, not a model, counts its distinct rows. Override for estimated counts on huge tables.

authorize(action: str, obj: ModelT | None = None, data: Any = None) → None#

Decide whether the caller may do action. The default allows everything.

Restly calls it for every action, before anything changes:

  • get_many: before the load. obj and data are None.

  • get_one: after the scoped load. obj is the row.

  • create: obj is None, and data is the request body.

  • update: after the scoped load. obj is the row, and data is the request body.

  • delete: after the scoped load. obj is the row.

  • every write_action(): obj is its row, or None for a new object or for no single row. data is its data.

Override it to enforce a policy: raise fr.exc.Forbidden or fr.exc.NotFound to refuse. Row visibility, hiding a row from every caller, belongs in the scope, not here.

before_action_commit(action: str, new: ModelT | None, old: dict[str, Any] | None = None) → None#

In-transaction side effect (outbox rows, audit rows), committed atomically with the write. old is the pre-mutation snapshot dict.

after_action_commit(action: str, new: ModelT | None, old: dict[str, Any] | None = None) → None#

Post-commit side effect (email, webhook, cache invalidation). old enables dirty detection (“notify only if the status changed”).

For external effects only: the write is already durable, so mutating new or the database here is NOT persisted. A mutation to new also leaks into this request’s response (which serializes new after this hook) while being silently discarded from storage. Do the mutation in the business method or before_action_commit instead.

An exception here cannot undo the committed write, yet it fails the request, so a client that retries repeats the write. Catch and log the errors of a best-effort effect here; add an effect that must happen as an outbox row in before_action_commit.

class fastapi_restly.views.AsyncRestView#

Bases: BaseRestView[ModelT, ResponseSchemaT, CreateSchemaT, UpdateSchemaT, IdT]

AsyncRestView creates an async CRUD/REST interface for database objects. Basic usage:

class FooView(AsyncRestView):
    prefix = "/foo"
    schema = FooSchema
    model = Foo

Each CRUD route runs through three methods (see “CRUD Routes” in the docs):

  • <verb>_endpoint: the endpoint method. Owns the HTTP signature, and response_model. Override it to change the HTTP contract.

  • handle_<verb>: the handler. Handles the steps: authorize, the load or the business method, and the commit bracket (before_action_commit -> commit -> after_action_commit); returns the domain object. Call it from a custom route to run the same steps. You cannot override it.

  • create / update / delete: the business method. Auth-free, commit-free; the common override point (hash a password, …). It changes objects in the session and does not flush: the commit bracket saves.

get_one and get_many are the loads. As with the handlers, you cannot override them. They start from select(): the scope and the loader options. Change a load through scope, where_id, not_found, apply_list_params and get_loader_options.

session: AsyncSessionDep#

The SQLAlchemy AsyncSession of this request, from fr.AsyncSessionDep. To use another database on one view, give the attribute another annotation; see Use another database on one view.

async get_many_endpoint(list_params: Any) → ViewListResponse#

GET / endpoint method. Put the rows in scope, and the list params in apply_list_params. Restly builds the response with to_list_response. Replace this method only to change the HTTP contract.

async get_one_endpoint(id: IDType) → ViewResponse#

GET /{id} endpoint method. Put the rows in scope, and the lookup of the id in where_id. Restly builds the response with to_single_response. Replace this method only to change the HTTP contract.

async create_endpoint(data: ViewCreate) → ViewResponse#

POST / endpoint method. Override create for domain logic (it is commit-free; the handler owns the commit). Restly builds the response with to_single_response. Replace this method only to change the HTTP contract.

async update_endpoint(id: IDType, data: ViewUpdate) → ViewResponse#

PATCH /{id} endpoint method. Override update for domain logic. Restly builds the response with to_single_response. Replace this method only to change the HTTP contract.

async delete_endpoint(id: IDType) → None#

DELETE /{id} endpoint method. Override delete for domain logic (e.g. soft delete); replace this method only to change the HTTP contract (e.g. return the deleted object instead of 204).

async handle_get_many(list_params: Any, *, scope: WhereClause | None = None, where: ColumnElement[bool] | WhereClause | None = None) → ListResult[ModelT]#

List handler: authorize, then the get_many load.

You cannot override it, as with every handler: authorize is the gate, and the list params and the scope decide the rows. Call it from a custom list route.

Parameters:
  • scope – a clause that replaces the view scope for this read, so a custom route can list another surface of the same model (a trash list); fr.clauses.UNSCOPED reads past it. Forwarded to get_many.

  • where – a SQLAlchemy boolean expression or a clause that narrows this read inside the scope, so a nested list keeps the visibility rules (where=Task.project_id == id). The page and total_count both apply it. Forwarded to get_many.

Raises:

TypeError – where is a Python bool (a comparison on a loaded object), or neither an expression nor a clause.

async handle_get_one(id: IdT | ColumnElement[bool], *, scope: WhereClause | None = None) → ModelT#

Retrieve handler: scoped load (404 by visibility) then read-auth.

You cannot override it: authorize is the gate, and where_id and not_found shape the load. Call it from a custom read route as “load with scope + 404 + read-auth”. A write action instead loads with get_one(id, scope=...) and gates only its own action, the way handle_update and handle_delete do.

Parameters:
  • id – the id from the path, which where_id turns into the WHERE, or a SQLAlchemy boolean expression that picks the row instead, so a natural-key route is this handler with Item.slug == slug. Forwarded to get_one.

  • scope – a clause that replaces the view scope for this read, so a restore route can load the row the view scope hides. Forwarded to get_one.

write_action(action: str, *, obj: Any, data: Any = None) → AbstractAsyncContextManager[None]#

Run one write action of a custom route: authorize, the reference check, your change, the save and the commit.

obj is the row that the action is about. It is required:

  • A row from the database, such as one from get_one. The block changes it. authorize gets the row, and old is its snapshot:

    async with self.write_action(self.Action.PUBLISH, obj=post):
        post.published = True
    
  • A new object that is not in the database yet: the action creates it. Restly adds it to the session when the block starts, so a flush in the block gives it an id. authorize gets obj=None, as on POST /, and old is None. Pass the request as data, so that authorize sees what the action creates. Do not session.add() the object before the block, and do not append it to a collection of a loaded row there: the block begins with a flush, so an error in the block would not undo that row:

    upload = Upload(filename=file.filename)
    async with self.write_action(self.Action.CREATE, obj=upload, data=form):
        await self.session.flush()  # upload.id, for the lines
        self.session.add_all(UploadLine(upload_id=upload.id) ...)
    
  • None: the action has no single row, such as a change to several rows. authorize gets obj=None, and the hooks get new=None and old=None.

action is the name that authorize and the hooks get. It is one of the names that the view’s Action class declares, such as self.Action.PUBLISH. data goes to authorize, and Restly checks the references in it, as a CRUD write does: the MustExist, IDRef and IDSchema fields, also in nested schemas and in each item of a list. A missing row raises NotFound (404).

The block runs under session.no_autoflush: nothing is written until the block ends, and a query in the block does not see your unflushed changes. When the block ends, Restly flushes the session. Then it refreshes obj and every other row of the view’s model that the action wrote, and loads them with get_loader_options(), so the route can return them. When the block deleted obj, as a merge deletes its source, new is None. Then Restly runs before_action_commit(action, new, old), commits, and runs after_action_commit(action, new, old). The block gets nothing from as. Code after the block runs after the commit, but not when the block runs inside another block: then it runs before the commit. Work that needs the commit goes in after_action_commit.

An exception in the block skips the save and the commit. The outermost block runs in a savepoint, and Restly rolls back to it, so what the block changed is undone. The outermost block on the session owns the commit and the after-hooks. So a handler or a write_action inside this block, or this block inside shared_write_action_commit(), returns after its save and before_action_commit. Its save also writes the changes of this block so far, so set the required values of the block’s objects before you call it. An IntegrityError from authorize to the commit becomes Conflict (409) when it leaves the outermost block, and stays raw inside it. A direct session.commit() inside the block raises RuntimeError. When the outermost block is a write action of a view with atomic_write_actions = False, code in the block may commit, and there is no savepoint: an error rolls back all that is not committed.

Raises:
  • ValueError – the view’s Action does not declare action.

  • TypeError – obj is neither None nor an object of a SQLAlchemy model.

shared_write_action_commit() → AbstractAsyncContextManager[None]#

Share one commit across write actions on this session.

The outermost block commits once, then runs the queued after_action_commit hooks. write_action and the write handlers still authorize, check the references, change, save, and run before_action_commit. They return uncommitted objects inside the block:

async with self.shared_write_action_commit():
    for item in items:
        await self.handle_create(item)

Serialize returned objects and run code that depends on an after-hook only after the block exits. Nested blocks on the same session share the commit. An exception escaping a deferred-commit block aborts the shared commit, including when an enclosing deferred-commit block catches that exception. A write action that raises after it changed objects stops the commit too, unless the rollback of a savepoint around it undid the change: run each write that a route may refuse in session.begin_nested(). The outermost block runs in a savepoint of its own. When an exception leaves it, Restly rolls back to that savepoint: the changes of the block are undone, and the session can write again. An IntegrityError inside the block stays raw, so a route can catch the error of one row; one that escapes the outermost block, or that its commit raises, becomes Conflict (409).

After-hooks run in queue order and stop on the first exception. new is the live object after all writes, while old is each action’s snapshot. Direct session.commit() calls raise RuntimeError, unless the block is inside a write action of a view with atomic_write_actions = False. An async write action needs an async outermost block; a sync one joins either.

async handle_create(data: CreateSchemaT) → ModelT#

Create handler: authorize, the reference check, create, commit bracket.

You cannot override it. Override create for the domain change, authorize for the gate, and before_action_commit / after_action_commit for side effects. authorize gets the payload, and no row. The object that create returns is the subject of the action: the save adds it, flushes, refreshes it, and the hooks get it as new. Call this from a custom create route, and from inside shared_write_action_commit() to share one commit with other writes; it then returns after the save, before the commit.

Raises:

TypeError – create returned None.

async handle_update(id: IdT | ColumnElement[bool], data: UpdateSchemaT) → ModelT#

Update handler: scoped load, then update in the commit bracket.

You cannot override it, as with handle_create(): update receives the loaded object, so the load, the 404, authorize and the reference check stay here. old is the snapshot of the loaded row, and new is the object that update returns, after the save. Inside shared_write_action_commit() it returns before the commit.

Raises:

TypeError – update returned None.

async handle_delete(id: IdT | ColumnElement[bool]) → None#

Delete handler: scoped load, then delete in the commit bracket.

You cannot override it, as with handle_create(). The loaded row is the subject. After a hard delete, the hooks get new=None. A soft delete flips a timestamp in delete and keeps the row, so the hooks get the row as new. An off-request follow-up runs in after_action_commit. Inside shared_write_action_commit(), the change runs at once, and the after-hook waits for the outermost block to commit.

async get_many(list_params: Any, *, scope: WhereClause | None = None, where: ColumnElement[bool] | WhereClause | None = None) → ListResult[ModelT]#

The load of the list: the rows the scope allows, filtered and paged by list_params.

You cannot override it. It is auth-free: handle_get_many adds authorize. The statement is select(), then apply_list_params(). A paginated view also runs count() for total_count; a view without pagination returns every matching row with total_count=None. Override apply_list_params to filter, sort or page in another way, and to_single_response to add a value to each row.

Parameters:
  • list_params – the list params (filter, sort, page) as the endpoint receives them. A QueryParams or a mapping goes through list_params_schema first, as on the list route.

  • scope – a clause that replaces the view scope for this read; fr.clauses.UNSCOPED reads unscoped.

  • where – a SQLAlchemy boolean expression or a clause that narrows this read inside the scope.

Raises:

TypeError – where is a Python bool (a comparison on a loaded object), or neither an expression nor a clause.

async get_one(id: IdT | ColumnElement[bool], *, scope: WhereClause | None = None) → ModelT#

The load of one row: the row id names, through the scope, or the exception of not_found().

You cannot override it. It is auth-free: handle_get_one adds authorize; a write action calls this directly and gates its own action. The statement is select() with where_id(), so a row outside the scope is a 404 for every caller. Override where_id to find the row by another key, and not_found to change the 404.

Parameters:
  • id – the id from the path, or a SQLAlchemy boolean expression that picks the row instead (get_one(Item.slug == slug)). An expression narrows inside the scope; only scope= replaces it.

  • scope – a clause that replaces the view scope for this read; fr.clauses.UNSCOPED reads unscoped.

Raises:
  • fastapi_restly.exc.NotFound – no row matches inside the scope, or the exception that not_found returns.

  • sqlalchemy.exc.MultipleResultsFound – more than one row matches; an ambiguous key is a bug in the criterion.

  • TypeError – id is a Python bool (a comparison on a loaded object, which would render as WHERE true), an uncalled clause (a scope, not a row identity), or an expression on a table that the query does not select from; or where_id or not_found returned a value of the wrong kind.

async create(data: CreateSchemaT) → ModelT#

Build a new object from data and return it.

Auth-free, flush-free and commit-free: handle_create checks the references before this method, and saves and commits after it. The default is fr.objects.async_make_new_object with the view’s model: it adds the object to the session, without a flush, so the object has no id yet. Override to change the object before the save (hash a password from the request): call super().create(), change the object, and return it.

Nothing is written until the save after this method: the handler runs it under session.no_autoflush, so a query here does not flush the new object, and it does not see your unflushed changes. Call await self.session.flush() when you need the id inside this method. A direct call, outside handle_create, writes nothing.

async update(obj: ModelT, data: UpdateSchemaT) → ModelT#

Apply data to the loaded obj and return it.

Auth-free, flush-free and commit-free: handle_update loads obj through get_one, gates, checks the references, and saves and commits after this method. The default is fr.objects.async_update_object. Override to check the stored row first, or to change the object after super().update(). As in create, nothing is written before the save, and a direct call writes nothing.

async delete(obj: ModelT) → None#

Mark obj for deletion. Does not flush or commit: handle_delete does.

Override (on the view or on a soft-delete mixin) to flip a timestamp instead of removing the row, without calling super(). A raw row delete elsewhere is fr.objects.async_delete_object(self.session, obj).

async apply_list_params(stmt: Select, list_params: Any) → Select#

Apply the list params to stmt: apply_filters(), then the sort, then the page.

Async, as apply_filters() is: call it with await. Override for list params of your own; the common case is driven by configuration. A QueryParams or a mapping goes through list_params_schema first, as on the list route. In a QueryParams, a key that the route reads is left out. Any other key that the list params do not have raises RequestValidationError, as on the list route (see unknown_query_params).

async apply_filters(stmt: Select, list_params: Any) → Select#

Apply the filters of list_params to stmt, without the sort and the page.

For a route that reads the client’s filters but has its own order or no rows to page, such as a count per category with GROUP BY. Like every custom read route, such a route calls authorize() and starts from select(), which applies the scope. apply_list_params() calls this method first. A QueryParams or a mapping goes through list_params_schema first, as on the list route. In a QueryParams, a key that the route reads is left out. Any other key that the list params do not have raises RequestValidationError, as on the list route (see unknown_query_params).

The generated filters come first, then the view’s own filters from list_filter(), in the order of the class.

async count(stmt: Select) → int#

Total for the list, ignoring presentation-layer ordering/pagination.

It counts the distinct primary keys of the model that stmt selects, without its order and page. So a join to a to-many relationship does not count a row twice. No other column is part of the count, so a json column works on PostgreSQL, and the subquery of a column_property does not run for every row. A stmt that selects columns, not a model, counts its distinct rows. Override for estimated counts on huge tables.

async authorize(action: str, obj: ModelT | None = None, data: Any = None) → None#

Decide whether the caller may do action. The default allows everything.

Restly calls it for every action, before anything changes:

  • get_many: before the load. obj and data are None.

  • get_one: after the scoped load. obj is the row.

  • create: obj is None, and data is the request body.

  • update: after the scoped load. obj is the row, and data is the request body.

  • delete: after the scoped load. obj is the row.

  • every write_action(): obj is its row, or None for a new object or for no single row. data is its data.

Override it to enforce a policy: raise fr.exc.Forbidden or fr.exc.NotFound to refuse. Row visibility, hiding a row from every caller, belongs in the scope, not here.

async before_action_commit(action: str, new: ModelT | None, old: dict[str, Any] | None = None) → None#

In-transaction side effect (outbox rows, audit rows), committed atomically with the write. old is the pre-mutation snapshot dict.

async after_action_commit(action: str, new: ModelT | None, old: dict[str, Any] | None = None) → None#

Post-commit side effect (email, webhook, cache invalidation). old enables dirty detection (“notify only if the status changed”).

For external effects only: the write is already durable, so mutating new or the database here is NOT persisted. A mutation to new also leaks into this request’s response (which serializes new after this hook) while being silently discarded from storage. Do the mutation in the business method or before_action_commit instead.

An exception here cannot undo the committed write, yet it fails the request, so a client that retries repeats the write. Catch and log the errors of a best-effort effect here; add an effect that must happen as an outbox row in before_action_commit.

class fastapi_restly.views.AsyncReactAdminView#

Bases: AsyncRestView

AsyncRestView that follows the ra-data-simple-rest HTTP contract.

Use this instead of AsyncRestView when your frontend is react-admin with ra-data-simple-rest.

async get_many_endpoint(list_params: Any) → ViewListResponse#

GET / endpoint method. Put the rows in scope, and the list params in apply_list_params. Restly builds the response with to_list_response. Replace this method only to change the HTTP contract.

async apply_list_params(stmt: Select, list_params: Any) → Select#

Apply the react-admin list params to the scoped base statement: apply_filters(), then sort and range.

async apply_filters(stmt: Select, list_params: Any) → Select#

Apply the react-admin filter to stmt, without the sort and the range.

async put(id: IDType, data: ViewUpdate) → ViewResponse#

PUT /{id} endpoint method, for react-admin’s update. It runs the same steps as PATCH: handle_update(), with the view’s update_schema body. An update override changes both routes. Replace this method to give PUT its own rules; see Give PUT its own rules.

list_params_schema: ClassVar[type[pydantic.BaseModel]] = ReactAdminListParams#

The list params (filter, sort, page) as a pydantic model, generated from response_schema and model by derive_list_params_schema(). Any route method on the view that declares a list_params parameter takes it: typed for FastAPI and OpenAPI, and guarded against unknown keys like GET /, so a custom list route (a trash route naming its own scope) reads the same list params. The route can take other query parameters beside it.

pagination: ClassVar[Pagination | None] = NumberedPagination(default_page_size=25)#

Only default_page_size and max_page_size apply: the implicit page size when no range parameter is sent, and the most rows one range may ask for. Override per view.

list_response_schema: ClassVar[Any]#

A react-admin list is a JSON array, without an envelope.

get_react_admin_range_unit() → str#

Return the unit string used in the Content-Range header.

to_list_response(list_result: ListResult[Any]) → Response#

Build the react-admin list response: a JSON array with a Content-Range header.

classmethod before_include_view() → None#

Apply type annotations needed for FastAPI, before creating an APIRouter from this view and registering it.

This function can be overridden to further tweak the endpoints before they are added to FastAPI.

class fastapi_restly.views.ReactAdminView#

Bases: RestView

RestView that follows the ra-data-simple-rest HTTP contract.

Use this instead of RestView when your frontend is react-admin with ra-data-simple-rest.

get_many_endpoint(list_params: Any) → ViewListResponse#

GET / endpoint method. Put the rows in scope, and the list params in apply_list_params. Restly builds the response with to_list_response. Replace this method only to change the HTTP contract.

apply_list_params(stmt: Select, list_params: Any) → Select#

Apply the react-admin list params to the scoped base statement: apply_filters(), then sort and range.

apply_filters(stmt: Select, list_params: Any) → Select#

Apply the react-admin filter to stmt, without the sort and the range.

put(id: IDType, data: ViewUpdate) → ViewResponse#

PUT /{id} endpoint method, for react-admin’s update. It runs the same steps as PATCH: handle_update(), with the view’s update_schema body. An update override changes both routes. Replace this method to give PUT its own rules; see Give PUT its own rules.

list_params_schema: ClassVar[type[pydantic.BaseModel]] = ReactAdminListParams#

The list params (filter, sort, page) as a pydantic model, generated from response_schema and model by derive_list_params_schema(). Any route method on the view that declares a list_params parameter takes it: typed for FastAPI and OpenAPI, and guarded against unknown keys like GET /, so a custom list route (a trash route naming its own scope) reads the same list params. The route can take other query parameters beside it.

pagination: ClassVar[Pagination | None] = NumberedPagination(default_page_size=25)#

Only default_page_size and max_page_size apply: the implicit page size when no range parameter is sent, and the most rows one range may ask for. Override per view.

list_response_schema: ClassVar[Any]#

A react-admin list is a JSON array, without an envelope.

get_react_admin_range_unit() → str#

Return the unit string used in the Content-Range header.

to_list_response(list_result: ListResult[Any]) → Response#

Build the react-admin list response: a JSON array with a Content-Range header.

classmethod before_include_view() → None#

Apply type annotations needed for FastAPI, before creating an APIRouter from this view and registering it.

This function can be overridden to further tweak the endpoints before they are added to FastAPI.

class fastapi_restly.views.ReactAdminListParams(*, sort: Annotated[tuple[str, Literal['ASC', 'DESC']], Json] | None = None, range: Annotated[tuple[int, int], Json] | None = None, filter: Annotated[dict[str, Any], Json] | None = None)#

Bases: BaseModel

The list params of a react-admin view: sort, range and filter.

React-admin sends each key as JSON in the query string. The fields are pydantic.Json, so the view and your overrides get the parsed values: sort as ("name", "DESC"), range as (0, 24) and filter as a dict. JSON that does not have this shape gets a 422 that names the place, as a bad value of other list params does.

To add a query key, such as a search key, subclass this class and set the subclass as the view’s list_params_schema.

sort: Annotated[tuple[str, Literal['ASC', 'DESC']], Json] | None#

The sort order: a field name and "ASC" or "DESC", such as ("name", "DESC"). None when the request has no sort.

range: Annotated[tuple[int, int], Json] | None#

The first and the last row to return, both included, such as (0, 24). None when the request has no range.

filter: Annotated[dict[str, Any], Json] | None#

The filters, as a dict from a field name to a value. None when the request has no filter.

class fastapi_restly.views.BaseRestView#

Bases: View

The part that RestView and AsyncRestView share: the settings, the read statement and the response methods.

It has no routes, no handlers and no business methods. Those are on RestView and AsyncRestView, in a sync and an async form. Subclass this class only to write a CRUD base class of your own.

schema: ClassVar[type[BaseModel]]#

The main schema: the Pydantic class that lists the fields of the resource. Restly builds response_schema, create_schema and update_schema from it. When a view sets none, Restly generates it from model with derive_schema().

response_schema: ClassVar[type[BaseModel]]#

The class of everything that goes out: the single responses, the items of the list response, and the fields the list params filter and sort on. The relationships it names are the ones the view loads. When a view sets none, Restly builds it with derive_response_schema(): the main schema without its WriteOnly fields, named <Resource>Response. A class that a view sets is used as it is.

list_response_schema: ClassVar[Any]#

The class of the list response: what GET / and a route that declares ViewListResponse send. When a view sets none, Restly builds it with derive_list_response_schema(): the envelope of the view’s pagination, with the response schema as its items, named <Resource>ListResponse. Restly fills a class that a view sets as it fills an envelope: by field name, from the values of the view’s pagination, such as data, total_count, page, page_size and total_pages. A view that replaces get_many_endpoint can set any type here.

create_schema: ClassVar[type[BaseModel]]#

The class of the POST body. When a view sets none, Restly builds it from the main schema without its ReadOnly fields and without a primary key that the server generates. It is named <Resource>Create. A class that a view sets is used as it is.

update_schema: ClassVar[type[BaseModel]]#

The class of the PATCH body. When a view sets none, Restly builds it from the main schema without its ReadOnly fields and without a primary key that the server generates, and makes every other field optional. It is named <Resource>Update. A class that a view sets is used as it is.

model: ClassVar[type[Any]]#

The SQLAlchemy model that the view serves: a mapped class. A view that you register needs it. A class that is not mapped raises RestlyConfigurationError when Python creates the view class.

scope: ClassVar[WhereClause | None] = None#

The clause every read on this view applies: list, count, and retrieve (a row outside it is 404). None (the default) falls back to the model’s declared default_scope; fr.clauses.UNSCOPED reads unscoped despite that default. Declaring a scope replaces the default, it does not stack on it; compose the replacement from the same leaves (ItemClauses.trashed containing the tenant clause visible contains). A rule that must hold under every scope is a session-level with_loader_criteria, not a view concern (see the Multi-Tenancy guide). See the Scopes guide for scopes.

id_type: ClassVar[type[Any] | None] = None#

The type of the {id} path parameter on the default routes. None (the default) takes the Python type of the model’s primary key, and a composite key gets int. Set a type to override it. Built-in item routes use Starlette’s int or uuid path converter for those types. Integer paths accept non-negative digits. An unmatched value falls through to another route or returns 404, instead of 422.

unknown_query_params: ClassVar[Literal['forbid', 'ignore']] = 'forbid'#

What a list route does with a query key that it does not read. "forbid" (the default) rejects the request with 422, so a typo in a filter key does not return more rows than the client asked for. "ignore" leaves the key out, as FastAPI does. The values are those of Pydantic’s extra setting. The same rule applies to a QueryParams that a method gets as list params.

pagination: ClassVar[Pagination | None] = NumberedPagination()#

How list endpoints paginate. The default NumberedPagination takes page / page_size query parameters, runs the count query, and wraps the list in its envelope (NumberedEnvelope: data plus total_count / page / page_size / total_pages). An OffsetPagination does the same with limit / offset query parameters (OffsetEnvelope: data plus total_count / limit / offset). A NoPagination returns every matching row with no count, in its envelope; None is short for NoPagination(), a plain Envelope (data only). A view inherits it, so a project base view sets it once; a view that differs changes one setting with replace() on the shared settings. For a shape no envelope model can express, such as a header, replace get_many_endpoint with a matching response_model (see AsyncReactAdminView).

include_filters: ClassVar[tuple[str, ...]] = ('*',)#

The filter keys that the list params keep, from the keys that Restly generates from response_schema. An entry is a key with the Python name of its field, such as "name__icontains", also for a field with an alias, or a pattern. * matches any characters except ., so "created_at__*" is every filter on created_at with a suffix, and "vendor.*" is every key on the fields of vendor. The default, ("*",), keeps the keys of the resource’s own fields, and no dotted keys. () keeps none. An entry that the view sets and that matches no key fails when the view registers. So does an entry with the name in the URL of a field with an alias, also when the view inherits it.

exclude_filters: ClassVar[tuple[str, ...]] = ()#

The filter keys that the list params leave out, after include_filters. The entries are the same as there, but a name without a suffix leaves out the whole field: the plain key and each key with a suffix. So ("name",) also removes name__in.

include_sort_keys: ClassVar[tuple[str, ...]] = ('*',)#

The keys that sort accepts: the Python name of a field, such as "name" or "vendor.name", or a pattern as in include_filters. The default, ("*",), is the resource’s own fields. A sort key never goes through a to-many relationship. With (), the list has no sort parameter.

exclude_sort_keys: ClassVar[tuple[str, ...]] = ()#

The sort keys to leave out, after include_sort_keys.

sort_query_param: ClassVar[str] = 'sort'#

The name of the sort parameter. Set it to keep the URLs of another library, such as "ordering" for Django REST framework or "order_by" for fastapi-filter. The old name is then free for a filter key.

default_sort: ClassVar[str | None] = None#

The sort when the request has none, written as ?sort= with the Python names of the fields, such as "-created_at". It becomes the default of the sort parameter, with the names in the URL, so OpenAPI shows it. A key must be a field of response_schema that a sort key could have, but include_sort_keys does not have to keep it. Use each key only once. None (the default) sorts by the primary key. The primary key is always the last term. A view that inherits it and does not have all its keys fails when it registers.

sort_nulls: ClassVar[Literal['first', 'last'] | None] = 'last'#

Where a sort puts NULLs: "last" (the default) or "first" in both directions, on every database. None leaves them where the database puts them, which differs: PostgreSQL puts them last in an ascending sort, SQLite and MySQL first.

list_params_schema: ClassVar[type[BaseModel]]#

The list params (filter, sort, page) as a pydantic model, generated from response_schema and model by derive_list_params_schema(). Any route method on the view that declares a list_params parameter takes it: typed for FastAPI and OpenAPI, and guarded against unknown keys like GET /, so a custom list route (a trash route naming its own scope) reads the same list params. The route can take other query parameters beside it.

atomic_write_actions: ClassVar[bool] = True#

Whether each write action of this view is one transaction. True (the default) refuses a session.commit() in the action, and an error undoes all of its work. False allows that commit, for code that must keep it, such as a library, or a function that a job also calls. All else stays, but the action is no longer one transaction: what is committed stays saved when a later step raises, and after_action_commit does not run then. There is no savepoint, so an error rolls back all that is not committed, also the work of the route before the action. The outermost write action decides for the actions inside it, and an outermost shared_write_action_commit() block always refuses a commit. See “Code that must commit in a write action” in the Lifecycle guide.

request: Request#

The fastapi.Request of the current request, which Restly sets for each request. After include_view(), a view that you create yourself must get request= (None outside a request) and session=.

select(*, scope: WhereClause | None = None) → Select#

The statement of the view’s rows: select(model), the scope, and get_loader_options().

get_one and get_many start here, and so does a custom route that builds its own read: self.select().where(Item.price > 10). The rows are the ones the view shows, and each row loads what the response needs. You cannot override it: set scope to change the rows, and override get_loader_options() to change the loads.

Parameters:

scope – a clause that replaces the view scope for this statement; fr.clauses.UNSCOPED reads past it.

where_id(id: Any) → ColumnElement[bool]#

The WHERE that picks the row an id from a path names.

The default compares the primary key: Item.id == id. Override to find the row by another key, such as a slug. Every load by id uses it: GET, PATCH and DELETE /{id}, and self.get_one(id) in your routes:

def where_id(self, id: str) -> ColumnElement[bool]:
    return Recipe.slug == id

A model with a composite primary key needs an override: set id_type = str, split the id from the path, and return and_(...). The expression must name the view’s model, not another table, and it runs no query, so define it with def, also on an async view.

not_found(id: Any) → Exception#

The exception for an id that names no row: a 404 by default, such as User with id 5 was not found. The name is the resource of the main schema, as in the names of the schemas that Restly generates.

get_one raises what this returns, so an override can change the text or the status, such as 410 for a row that was deleted. On an async view it may be async def, and Restly awaits it. id is the id from the path, or None when a route loaded by an expression, such as handle_get_one(Item.slug == slug).

get_loader_options() → list[Any]#

The loader options of every read: what each row loads.

The default is a recursive selectinload(...) for each relationship that response_schema names. select() applies them, so get_one, get_many and your routes load the same, and so does the reload after the save of a write. Override to load more: a relationship that the response schema does not name, or a query_expression through with_expression(...). Add to super().get_loader_options() to keep the default loads. See “Return related objects in a response” on the Relationships guide page.

to_single_response(obj: ModelT | ResponseSchemaT) → ResponseSchemaT#

Serialize one ORM object to the view’s response_schema.

By default the response schema is the main schema without its WriteOnly fields, named like UserResponse. An override may return an instance of another model, such as schema. Only the fields of the response schema go out. Restly copies the values of an instance of a subclass of the response schema, and of schema when Restly derived the response schema, without validating them again. It validates any other model into the response schema from its attributes.

The view loads only the relationships that the response schema names. An override that builds schema from the ORM object also reads the relationships of its WriteOnly fields. On an async view that fails with MissingGreenlet: add them in get_loader_options(), or build the response schema instead.

The ORM path below validates through the response schema, so a view’s main schema that declares a WriteOnly field the ORM object doesn’t carry (e.g. password backed by a password_hash column) doesn’t fail response validation. It validates in lax mode, also for a strict class, so a strict float field reads the text "NaN" that a JSON column stores.

to_list_response(list_result: ListResult[ModelT]) → Any#

Build the list response body: an instance of list_response_schema.

By default this class is the envelope of the view’s pagination: a NumberedEnvelope (data plus total_count / page / page_size / total_pages), an OffsetEnvelope (data plus total_count / limit / offset), or an Envelope (data only) for a view without pagination. To change the shape, set list_response_schema or the pagination’s envelope. A list type, such as list[UserSummary], gives a list without the page values. For a Content-Range header, see AsyncReactAdminView: it overrides this method and sets list_response_schema to match.

The values of the page come from list_result.list_params.

snapshot(obj: Any) → dict[str, Any]#

The column values that are loaded on obj, passed as old to before_action_commit and after_action_commit to compare old and new values.

The default is snapshot(): a shallow copy, which shares a mutable value, such as a JSON dict, with the object. Override it to change what old holds, for example the state of a relationship before the change.

classmethod before_include_view()#

Apply type annotations needed for FastAPI, before creating an APIRouter from this view and registering it.

This function can be overridden to further tweak the endpoints before they are added to FastAPI.

class fastapi_restly.views.ListResult(objects: Sequence[ModelT], total_count: int | None = None, list_params: Any = None)#

Result returned by get_many before HTTP response formatting.

total_count is None for a list without pagination, which does not run the count query. list_params holds the list params that get_many received, so BaseRestView.to_list_response() can read the page from them.

objects: Sequence[ModelT]#

The rows that the list loaded: one page, or every row for a list without pagination.

total_count: int | None = None#

The number of rows that match the filters, on all pages. It is None for a list without pagination. A paginated list response sends None as 0.

list_params: Any = None#

The list params that get_many received. Pass on the list params that you received: BaseRestView.to_list_response() reads the values of the page from them, and without them it reports the first page on every page.

class fastapi_restly.views.NumberedPagination(*, envelope: type[BaseModel] = NumberedEnvelope, default_page_size: int = 50, max_page_size: int = 1000, max_page: int | None = None, page_query_param: str = 'page', page_size_query_param: str = 'page_size')#

Bases: Pagination

Page-number pagination: ?page=2&page_size=50.

Set an instance as a view’s pagination. Views inherit it, so a project base view sets it once, and a view that differs changes one setting with replace():

APP_PAGINATION = fr.NumberedPagination(
    page_size_query_param="size", max_page_size=100
)

class AppView(fr.AsyncRestView):
    pagination = APP_PAGINATION

class LogView(AppView):
    pagination = APP_PAGINATION.replace(
        default_page_size=10, max_page_size=10
    )

envelope is the list response model: a generic Pydantic model with one type parameter, which each view fills with its response schema. Restly fills its fields by name from data, total_count, page, page_size and total_pages. Leave a field out to drop it from the response, and rename one with an alias or an alias_generator. A model_validator(mode="before") receives those values as a dict and can reshape them, for example to nest the metadata. Creating the settings builds an empty page from the envelope, so a required field Restly cannot fill fails at startup instead of on a request. An envelope keeps the default extra setting: Restly passes it every page value and it keeps the fields it declares.

default_page_size: int = 50#

page_size when the client sends none.

max_page_size: int = 1000#

The largest page_size a client may ask for. A larger one returns 422.

max_page: int | None = None#

The largest page number a client may ask for. A larger one returns 422. None sets no limit of its own: then only a page whose offset is above 2**63 - 1 returns 422.

page_query_param: str = 'page'#

The query parameter that carries the page number.

page_size_query_param: str = 'page_size'#

The query parameter that carries the page size.

envelope: type[BaseModel] = NumberedEnvelope#

The list response model. NumberedEnvelope by default.

class fastapi_restly.views.OffsetPagination(*, envelope: type[BaseModel] = OffsetEnvelope, default_limit: int = 50, max_limit: int = 1000, max_offset: int | None = None, limit_query_param: str = 'limit', offset_query_param: str = 'offset')#

Bases: Pagination

Limit and offset pagination: ?limit=50&offset=100.

Set an instance as a view’s pagination. It works as NumberedPagination does: views inherit it, and replace() changes one setting. For a client that says skip:

class ItemView(fr.AsyncRestView):
    pagination = fr.OffsetPagination(
        offset_query_param="skip", default_limit=20, max_limit=100
    )

envelope works as for NumberedPagination, and Restly fills it by name from data, total_count, limit and offset. The names in the JSON do not follow the names in the URL: to send skip in the response too, give the field an alias.

default_limit: int = 50#

limit when the client sends none.

max_limit: int = 1000#

The largest limit a client may ask for. A larger one returns 422.

max_offset: int | None = None#

The largest offset a client may ask for. A larger one returns 422. None sets no limit of its own: then only an offset above 2**63 - 1 returns 422.

limit_query_param: str = 'limit'#

The query parameter that carries the limit.

offset_query_param: str = 'offset'#

The query parameter that carries the offset.

envelope: type[BaseModel] = OffsetEnvelope#

The list response model. OffsetEnvelope by default.

class fastapi_restly.views.NoPagination(*, envelope: type[BaseModel] = Envelope)#

Bases: Pagination

No pagination: a list returns every matching row and runs no count query.

pagination = None is the short form of NoPagination(). Set an instance to choose the list response model:

T = TypeVar("T")

class DataCount(pydantic.BaseModel, Generic[T]):
    data: list[T]
    total_count: int = pydantic.Field(alias="count")

class TagView(fr.AsyncRestView):
    pagination = fr.NoPagination(envelope=DataCount)

envelope works as for NumberedPagination, and Restly fills it by name from data and total_count, the number of rows. A generic pydantic.RootModel over the items whose before-validator returns data makes the list a bare JSON array.

envelope: type[BaseModel] = Envelope#

The list response model. Envelope by default.

class fastapi_restly.views.Pagination(*, envelope: type[BaseModel] = Envelope)#

Bases: ABC

The base class of the pagination settings: NumberedPagination, OffsetPagination and NoPagination.

Use it to annotate the setting on a project base view, so that a view below it can choose another style:

class AppView(fr.AsyncRestView):
    pagination: ClassVar[fr.Pagination | None] = fr.OffsetPagination()

You cannot create an instance of this class. A subclass of your own does not work yet: the methods that a style needs are private.

envelope: type[BaseModel] = Envelope#

The list response model.

replace(**changes: Any) → Self#

A copy with changes applied, checked like a new instance.

For a view that changes one setting of shared pagination settings:

pagination = APP_PAGINATION.replace(
    default_page_size=10, max_page_size=10
)
class fastapi_restly.views.Envelope(*, data: list[DataT])#

Bases: BaseModel

List response wrapper: {"data": [...]}.

The default envelope of NoPagination, for a view that returns every row. A paginated view uses its pagination’s envelope: NumberedEnvelope or OffsetEnvelope by default.

data: list[DataT]#

The rows of the list, each as an instance of the view’s response schema. A list, not a Sequence: Pydantic writes the rows of a Sequence field with the settings of the envelope, not with the settings of the response schema, such as ser_json_inf_nan.

class fastapi_restly.views.NumberedEnvelope(*, data: list[DataT], total_count: int, page: int, page_size: int, total_pages: int)#

Bases: Envelope

List response with page numbers: data plus pagination metadata.

The default envelope of NumberedPagination.

total_count: int#

The number of rows that match the filters, on all pages.

page: int#

The number of this page. The first page is 1.

page_size: int#

The largest number of rows on one page: the page size of the request, or the default page size.

total_pages: int#

The number of pages: total_count divided by page_size, rounded up. It is 0 when no row matches.

class fastapi_restly.views.OffsetEnvelope(*, data: list[DataT], total_count: int, limit: int, offset: int)#

Bases: Envelope

List response with a limit and an offset: data plus pagination metadata.

The default envelope of OffsetPagination.

total_count: int#

The number of rows that match the filters, on all pages.

limit: int#

The largest number of rows in this response: the limit of the request, or the default limit.

offset: int#

The number of matching rows before the first row of this response.

class fastapi_restly.views.Action#

The names of the five CRUD actions: the action that authorize gets. A write, such as CREATE or the action of a write_action block, also passes it to before_action_commit and after_action_commit. A read, GET_MANY or GET_ONE, has no commit, so it reaches only authorize.

Each view has a class Action that lists all its actions. It is this class, until a view adds actions of its own in a subclass:

class PostView(fr.AsyncRestView):
    class Action(fr.Action):
        PUBLISH = "publish"

An Action class has only actions. An action has an UPPER_CASE name, and its value is that name in lower case. write_action takes only a value that the view’s Action declares. A view with base classes that declare actions, such as a mixin, inherits from their Action classes too.

GET_MANY = 'get_many'#

Read a list, as GET / does. A read has no commit.

GET_ONE = 'get_one'#

Read one row, as GET /{id} does. A read has no commit.

CREATE = 'create'#

Create a row, as POST / does.

UPDATE = 'update'#

Update a row, as PATCH /{id} does.

DELETE = 'delete'#

Delete a row, as DELETE /{id} does.

fastapi_restly.views.ReadScope = WhereClause | None#

A per-read scope: None for the view’s own, a clause that replaces it for that read, or fr.clauses.UNSCOPED.

class fastapi_restly.views.View#

Class-based view primitive for FastAPI.

Group related endpoints on a class, share dependencies and metadata via class attributes, and let subclasses override individual route methods. Routes are bound at include_view() time, not at class-definition time, so subclassing works the way Python developers expect: override a method on a subclass and the override is what runs.

Most users will subclass RestView or AsyncRestView, which extend View with CRUD scaffolding. Use View directly for grouped non-CRUD endpoints (auth flows, custom RPC routes, etc.).

prefix: ClassVar[str]#

The URL prefix of every route. Each class in the hierarchy that sets one adds a segment, base first. Without a prefix, the routes are at the root.

tags: ClassVar[Iterable[str | Enum] | None] = None#

The OpenAPI tags of every route. When it is not set, the tag is the last part of the prefix in title case, so /order-items gives Order Items. Without a prefix, the tag is the class name. On a router with tags of its own, Restly makes no tag: the routes get the tags of the router, as a plain route on it does. Setting it replaces the tag that Restly makes.

dependencies: ClassVar[Any] = None#

FastAPI dependencies run for every route, without injecting a result. Each class in the hierarchy adds its own, base first, so a subclass cannot drop a base’s guard. A subclass that lists a base’s entry again runs it where it lists it.

responses: ClassVar[dict[int | str, dict[str, Any] | None]] = {}#

OpenAPI responses documented on every route. Each class in the hierarchy adds its own, and a subclass’s entry for a status code wins. A status set to None is left out, so {404: None} removes the 404 that a CRUD view documents on a route that can answer 404.

classmethod before_include_view() → None#

Run by include_view() once per class, before its routes are registered. A no-op here; override to adjust route methods first.

class fastapi_restly.views.SchemaType(fn: Callable[[Any], Any])#

A type that depends on the view: a function that gets the view class and returns the type.

A setting that takes a schema class also takes a SchemaType. Here each view gets a create schema of its own:

class ApiView(fr.AsyncRestView):
    create_schema = SchemaType(lambda view: with_tenant(view.schema))

A setting can also use it as a decorator:

class ApiView(fr.AsyncRestView):
    @SchemaType
    def create_schema(view):
        return with_tenant(view.schema)

In a route, it goes in the metadata of an annotation:

Single = Annotated[Any, SchemaType(lambda view: Data[view.response_schema])]


class ApiView(fr.AsyncRestView):
    @fr.get("/{id}")
    async def get_one_endpoint(self, id: IDType) -> Single: ...

Restly calls the function once for each view class, when something first reads the type. It can read any setting of the view, in any order. A setting must get a Pydantic class, and list_response_schema also takes a list type. A route can get any type that FastAPI accepts. The function can use a marker in what it returns, as in Data[ViewResponse].

Parameters:

fn – The function. It gets the view class and returns the type.

fn: Callable[[Any], Any]#
name: str | None#

The name of a marker of this module.

fastapi_restly.views.resolve_scope(target: type[Any] | BaseRestView[Any, Any, Any, Any, Any]) → WhereClause#

The scope a read applies, resolved down the ladder.

Pass a view, class or instance, for the visibility that view’s reads apply: its declared scope, the model’s default_scope when the view declares none, and fr.clauses.UNSCOPED when neither does. Pass a mapped model class for the model rung alone, which is what every reference check applies. The two answers differ wherever a view declares a scope, so code off the request path that wants what the API shows passes the view.

The result is a clause or fr.clauses.UNSCOPED, never None, so it composes without a branch:

stmt = fr.apply_clauses(
    select(Task).where(Task.project_id == id),
    fr.resolve_scope(TaskView),
)

Every read resolves here, so a route that applies the result sees the same rows as get_one and get_many. It resolves the scope and does not apply it: applying stays with the framework, and there is no apply-side override point.

Parameters:

target – a view class or instance, or a mapped model class.

Raises:
fastapi_restly.views.delete(path: str, **api_route_kwargs: Any) → Callable[[...], Any]#

Decorator to mark a View method as a DELETE endpoint.

Equivalent to:

@route(path, methods=["DELETE"], status_code=204, ... )
fastapi_restly.views.get(path: str, **api_route_kwargs: Any) → Callable[[...], Any]#

Decorator to mark a View method as a GET endpoint.

Equivalent to:

@route(path, methods=["GET"], status_code=200, ... )
fastapi_restly.views.include_view(parent_router: APIRouter | FastAPI, view_cls: V | None = None) → V | Callable[[V], V]#

Add a View class’s routes to a FastAPI app or APIRouter.

Prefer the direct call form from your app/router composition layer:

include_view(app, MyView)

For small apps, it can also be used as a decorator:

@include_view(app)
class MyView(AsyncRestView):
    ...

Registering a view on several parents mounts its routes on each; calling include_view again with a parent the view is already registered on is a no-op.

fastapi_restly.views.list_filter(key: str) → Callable[[_F], _F]#

Make a view method the filter for the query key key.

For a filter that the generated keys do not give:

@fr.list_filter("popular")
def filter_popular(self, value: bool) -> ColumnElement[bool]:
    popular = Item.view_count > 1000
    return popular if value else ~popular

The method takes one value after self. Its type becomes the type of the key in the list params, so OpenAPI shows it and a bad value gets 422. The docstring becomes the description of the key. Without a default, the view calls the method when the key has a value. With a default, it calls the method on every list request, with the default when the key is missing.

The method returns a SQLAlchemy condition, a clause or None for no condition. The view adds it to the statement with AND, inside the scope. The condition may use only the tables that are in the statement; use a relationship (.has()/.any()) for another table. On an async view the method can be async def.

The key is a name of your own, such as popular, or a field and an operator, such as name__length. The operator may be one that Restly generates for other fields, or a new one. Before the last __ comes a field with filters, as in the generated keys, such as vendor.name. The key is the key in the URL, so a field goes by its alias when it has one. The key settings, such as exclude_filters, use Python names.

The key is always on: include_filters and exclude_filters choose among the generated keys only. A subclass drops the key by setting the method name to None.

Raises:

RestlyConfigurationError – key is not a non-empty string, starts with _, is the name of a Pydantic model attribute, or has __ without one field before it and one operator without . after it. A key that is a page parameter, the sort parameter or a generated key that is on fails when the view registers, and so does a key with __ or . that does not start with a field with filters.

fastapi_restly.views.modify_route(path: str | None = None, **api_route_kwargs: Any) → Any#

Change the options of a route that the view inherits, and keep the rest.

Use it in the class body, under the name of the route method:

class TagView(fr.AsyncRestView):
    prefix = "/tags"
    model = Tag

    create_endpoint = fr.modify_route(status_code=200, name="create_tag")
    delete_endpoint = fr.modify_route(dependencies=[Depends(require_admin)])

It takes the arguments of a route decorator, such as post(): they go to FastAPI’s APIRouter.add_api_route(). path replaces the path of the route.

Each argument replaces the one of the inherited route. dependencies and responses add up, as they do on a view. dependencies run base first. responses add up per status code, and a status code set to None is left out. A status code without a body, such as 204, also removes the response model of the route.

It changes how a route is served, not what it sends. So response_model and the other response_model_* arguments raise RestlyConfigurationError. To change the response of the view, set response_schema or list_response_schema. To change the response of one route, write the route method.

This changes the route of this view and its subclasses. The route of the base class stays the same.

A name that is not an inherited route raises RestlyConfigurationError when the class is defined.

fastapi_restly.views.patch(path: str, **api_route_kwargs: Any) → Callable[[...], Any]#

Decorator to mark a View method as a PATCH endpoint.

Equivalent to:

@route(path, methods=["PATCH"], status_code=200, ... )
fastapi_restly.views.post(path: str, **api_route_kwargs: Any) → Callable[[...], Any]#

Decorator to mark a View method as a POST endpoint.

Equivalent to:

@route(path, methods=["POST"], status_code=201, ... )
fastapi_restly.views.put(path: str, **api_route_kwargs: Any) → Callable[[...], Any]#

Decorator to mark a View method as a PUT endpoint.

Equivalent to:

@route(path, methods=["PUT"], status_code=200, ... )
fastapi_restly.views.route(path: str, **api_route_kwargs: Any) → Callable[[...], Any]#

Mark a view method as an endpoint, with the HTTP method and the route options that you pass.

path and api_route_kwargs go to FastAPI’s APIRouter.add_api_route() when include_view() registers the view. Without methods=, the route is a GET with status 200, as in FastAPI. get(), post(), patch(), put() and delete() set the method and the status code for you.

Markers for the view’s own types#

A route names the types of its view with these markers. When the view registers, Restly puts the view’s own type in place of each marker, so a route on a base view gets the types of each subclass. A type checker reads each marker as Any. See Name the view’s schemas in a custom route. To build another type for each view, use SchemaType; see Make dynamic schemas that depend on the view.

fastapi_restly.views.IDType#

The view’s id type: id_type, else the type of the model’s primary key. A path parameter with this type gets the view’s path converter: {id:int} for int and {id:uuid} for UUID.

fastapi_restly.views.ViewResponse#

The view’s response schema, response_schema.

fastapi_restly.views.ViewListResponse#

The view’s list response, list_response_schema. Unless the view sets another class, this is the envelope of the view’s pagination, with items of the view’s response schema.

fastapi_restly.views.ViewCreate#

The view’s create schema, create_schema.

fastapi_restly.views.ViewUpdate#

The view’s update schema, update_schema.

See also

Views introduces the class-based view concept and hierarchy, and CRUD Routes explains how a CRUD route runs. The page of each route, such as Update, shows what you can change.