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:
<verb>_endpoint, the endpoint method: the@route, FastAPI signature andresponse_model. Replace only 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). Call it from a custom route. You cannot override it.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, andresponse_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_oneandget_manyare the loads. As with the handlers, you cannot override them. They start fromselect(): the scope and the loader options. Change a load throughscope,where_id,not_found,apply_list_paramsandget_loader_options.- session: SessionDep#
The SQLAlchemy
Sessionof this request, fromfr.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 inscope, and the list params inapply_list_params. Restly builds the response withto_list_response. Replace this method only to change the HTTP contract.
- get_one_endpoint(id: IDType) ViewResponse#
GET /{id}endpoint method. Put the rows inscope, and the lookup of the id inwhere_id. Restly builds the response withto_single_response. Replace this method only to change the HTTP contract.
- create_endpoint(data: ViewCreate) ViewResponse#
POST /endpoint method. Overridecreatefor domain logic (it is commit-free; the handler owns the commit). Restly builds the response withto_single_response. Replace this method only to change the HTTP contract.
- update_endpoint(id: IDType, data: ViewUpdate) ViewResponse#
PATCH /{id}endpoint method. Overrideupdatefor domain logic. Restly builds the response withto_single_response. Replace this method only to change the HTTP contract.
- delete_endpoint(id: IDType) None#
DELETE /{id}endpoint method. Overridedeletefor 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 theget_manyload.You cannot override it, as with every handler:
authorizeis 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.UNSCOPEDreads past it. Forwarded toget_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 andtotal_countboth apply it. Forwarded toget_many.
- Raises:
TypeError –
whereis 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:
authorizeis the gate, andwhere_idandnot_foundshape the load. Call it from a custom read route as “load with scope + 404 + read-auth”. A write action instead loads withget_one(id, scope=...)and gates only its own action, the wayhandle_updateandhandle_deletedo.- Parameters:
id – the id from the path, which
where_idturns into the WHERE, or a SQLAlchemy boolean expression that picks the row instead, so a natural-key route is this handler withItem.slug == slug. Forwarded toget_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.objis 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.authorizegets the row, andoldis 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.
authorizegetsobj=None, as onPOST /, andoldisNone. Pass the request asdata, so thatauthorizesees what the action creates. Do notsession.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.authorizegetsobj=None, and the hooks getnew=Noneandold=None.
actionis the name thatauthorizeand the hooks get. It is one of the names that the view’sActionclass declares, such asself.Action.PUBLISH.datagoes toauthorize, and Restly checks the references in it, as a CRUD write does: theMustExist,IDRefandIDSchemafields, also in nested schemas and in each item of a list. A missing row raisesNotFound(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 refreshesobjand every other row of the view’s model that the action wrote, and loads them withget_loader_options(), so the route can return them. When the block deletedobj, as a merge deletes its source,newisNone. Then Restly runsbefore_action_commit(action, new, old), commits, and runsafter_action_commit(action, new, old). The block gets nothing fromas. 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 inafter_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_actioninside this block, or this block insideshared_write_action_commit(), returns after its save andbefore_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. AnIntegrityErrorfromauthorizeto the commit becomesConflict(409) when it leaves the outermost block, and stays raw inside it. A directsession.commit()inside the block raisesRuntimeError. When the outermost block is a write action of a view withatomic_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
Actiondoes not declareaction.TypeError –
objis neitherNonenor an object of a SQLAlchemy model.
Share one commit across write actions on this session.
The outermost block commits once, then runs the queued
after_action_commithooks.write_actionand the write handlers still authorize, check the references, change, save, and runbefore_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. AnIntegrityErrorinside 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, becomesConflict(409).After-hooks run in queue order and stop on the first exception.
newis the live object after all writes, whileoldis each action’s snapshot. Directsession.commit()calls raiseRuntimeError, unless the block is inside a write action of a view withatomic_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
createfor the domain change,authorizefor the gate, andbefore_action_commit/after_action_commitfor side effects.authorizegets the payload, and no row. The object thatcreatereturns is the subject of the action: the save adds it, flushes, refreshes it, and the hooks get it asnew. Call this from a custom create route, and from insideshared_write_action_commit()to share one commit with other writes; it then returns after the save, before the commit.- Raises:
TypeError –
createreturnedNone.
- handle_update(id: IdT | ColumnElement[bool], data: UpdateSchemaT) ModelT#
Update handler: scoped load, then
updatein the commit bracket.You cannot override it, as with
handle_create():updatereceives the loaded object, so the load, the 404,authorizeand the reference check stay here.oldis the snapshot of the loaded row, andnewis the object thatupdatereturns, after the save. Insideshared_write_action_commit()it returns before the commit.- Raises:
TypeError –
updatereturnedNone.
- handle_delete(id: IdT | ColumnElement[bool]) None#
Delete handler: scoped load, then
deletein the commit bracket.You cannot override it, as with
handle_create(). The loaded row is the subject. After a hard delete, the hooks getnew=None. A soft delete flips a timestamp indeleteand keeps the row, so the hooks get the row asnew. An off-request follow-up runs inafter_action_commit. Insideshared_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_manyaddsauthorize. The statement isselect(), thenapply_list_params(). A paginated view also runscount()fortotal_count; a view without pagination returns every matching row withtotal_count=None. Overrideapply_list_paramsto filter, sort or page in another way, andto_single_responseto add a value to each row.- Parameters:
list_params – the list params (filter, sort, page) as the endpoint receives them. A
QueryParamsor a mapping goes throughlist_params_schemafirst, as on the list route.scope – a clause that replaces the view scope for this read;
fr.clauses.UNSCOPEDreads unscoped.where – a SQLAlchemy boolean expression or a clause that narrows this read inside the scope.
- Raises:
TypeError –
whereis 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
idnames, through the scope, or the exception ofnot_found().You cannot override it. It is auth-free:
handle_get_oneaddsauthorize; a write action calls this directly and gates its own action. The statement isselect()withwhere_id(), so a row outside the scope is a 404 for every caller. Overridewhere_idto find the row by another key, andnot_foundto 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; onlyscope=replaces it.scope – a clause that replaces the view scope for this read;
fr.clauses.UNSCOPEDreads unscoped.
- Raises:
fastapi_restly.exc.NotFound – no row matches inside the scope, or the exception that
not_foundreturns.sqlalchemy.exc.MultipleResultsFound – more than one row matches; an ambiguous key is a bug in the criterion.
TypeError –
idis a Python bool (a comparison on a loaded object, which would render asWHERE true), an uncalled clause (a scope, not a row identity), or an expression on a table that the query does not select from; orwhere_idornot_foundreturned a value of the wrong kind.
- create(data: CreateSchemaT) ModelT#
Build a new object from
dataand return it.Auth-free, flush-free and commit-free:
handle_createchecks the references before this method, and saves and commits after it. The default isfr.objects.make_new_objectwith 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): callsuper().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. Callself.session.flush()when you need the id inside this method. A direct call, outsidehandle_create, writes nothing.
- update(obj: ModelT, data: UpdateSchemaT) ModelT#
Apply
datato the loadedobjand return it.Auth-free, flush-free and commit-free:
handle_updateloadsobjthroughget_one, gates, checks the references, and saves and commits after this method. The default isfr.objects.update_object. Override to check the stored row first, or to change the object aftersuper().update(). As increate, nothing is written before the save, and a direct call writes nothing.
- delete(obj: ModelT) None#
Mark
objfor deletion. Does not flush or commit:handle_deletedoes.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 isfr.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
QueryParamsor a mapping goes throughlist_params_schemafirst, as on the list route. In aQueryParams, a key that the route reads is left out. Any other key that the list params do not have raisesRequestValidationError, as on the list route (seeunknown_query_params).
- apply_filters(stmt: Select, list_params: Any) Select#
Apply the filters of
list_paramstostmt, 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 callsauthorize()and starts fromselect(), which applies the scope.apply_list_params()calls this method first. AQueryParamsor a mapping goes throughlist_params_schemafirst, as on the list route. In aQueryParams, a key that the route reads is left out. Any other key that the list params do not have raisesRequestValidationError, as on the list route (seeunknown_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
stmtselects, 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 ajsoncolumn works on PostgreSQL, and the subquery of acolumn_propertydoes not run for every row. Astmtthat 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.objanddataareNone.get_one: after the scoped load.objis the row.create:objisNone, anddatais the request body.update: after the scoped load.objis the row, anddatais the request body.delete: after the scoped load.objis the row.every
write_action():objis its row, orNonefor a new object or for no single row.datais itsdata.
Override it to enforce a policy: raise
fr.exc.Forbiddenorfr.exc.NotFoundto 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.
oldis 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).
oldenables dirty detection (“notify only if the status changed”).For external effects only: the write is already durable, so mutating
newor the database here is NOT persisted. A mutation tonewalso leaks into this request’s response (which serializesnewafter this hook) while being silently discarded from storage. Do the mutation in the business method orbefore_action_commitinstead.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, andresponse_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_oneandget_manyare the loads. As with the handlers, you cannot override them. They start fromselect(): the scope and the loader options. Change a load throughscope,where_id,not_found,apply_list_paramsandget_loader_options.- session: AsyncSessionDep#
The SQLAlchemy
AsyncSessionof this request, fromfr.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 inscope, and the list params inapply_list_params. Restly builds the response withto_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 inscope, and the lookup of the id inwhere_id. Restly builds the response withto_single_response. Replace this method only to change the HTTP contract.
- async create_endpoint(data: ViewCreate) ViewResponse#
POST /endpoint method. Overridecreatefor domain logic (it is commit-free; the handler owns the commit). Restly builds the response withto_single_response. Replace this method only to change the HTTP contract.
- async update_endpoint(id: IDType, data: ViewUpdate) ViewResponse#
PATCH /{id}endpoint method. Overrideupdatefor domain logic. Restly builds the response withto_single_response. Replace this method only to change the HTTP contract.
- async delete_endpoint(id: IDType) None#
DELETE /{id}endpoint method. Overridedeletefor 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 theget_manyload.You cannot override it, as with every handler:
authorizeis 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.UNSCOPEDreads past it. Forwarded toget_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 andtotal_countboth apply it. Forwarded toget_many.
- Raises:
TypeError –
whereis 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:
authorizeis the gate, andwhere_idandnot_foundshape the load. Call it from a custom read route as “load with scope + 404 + read-auth”. A write action instead loads withget_one(id, scope=...)and gates only its own action, the wayhandle_updateandhandle_deletedo.- Parameters:
id – the id from the path, which
where_idturns into the WHERE, or a SQLAlchemy boolean expression that picks the row instead, so a natural-key route is this handler withItem.slug == slug. Forwarded toget_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.objis 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.authorizegets the row, andoldis 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.
authorizegetsobj=None, as onPOST /, andoldisNone. Pass the request asdata, so thatauthorizesees what the action creates. Do notsession.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.authorizegetsobj=None, and the hooks getnew=Noneandold=None.
actionis the name thatauthorizeand the hooks get. It is one of the names that the view’sActionclass declares, such asself.Action.PUBLISH.datagoes toauthorize, and Restly checks the references in it, as a CRUD write does: theMustExist,IDRefandIDSchemafields, also in nested schemas and in each item of a list. A missing row raisesNotFound(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 refreshesobjand every other row of the view’s model that the action wrote, and loads them withget_loader_options(), so the route can return them. When the block deletedobj, as a merge deletes its source,newisNone. Then Restly runsbefore_action_commit(action, new, old), commits, and runsafter_action_commit(action, new, old). The block gets nothing fromas. 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 inafter_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_actioninside this block, or this block insideshared_write_action_commit(), returns after its save andbefore_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. AnIntegrityErrorfromauthorizeto the commit becomesConflict(409) when it leaves the outermost block, and stays raw inside it. A directsession.commit()inside the block raisesRuntimeError. When the outermost block is a write action of a view withatomic_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
Actiondoes not declareaction.TypeError –
objis neitherNonenor an object of a SQLAlchemy model.
Share one commit across write actions on this session.
The outermost block commits once, then runs the queued
after_action_commithooks.write_actionand the write handlers still authorize, check the references, change, save, and runbefore_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. AnIntegrityErrorinside 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, becomesConflict(409).After-hooks run in queue order and stop on the first exception.
newis the live object after all writes, whileoldis each action’s snapshot. Directsession.commit()calls raiseRuntimeError, unless the block is inside a write action of a view withatomic_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
createfor the domain change,authorizefor the gate, andbefore_action_commit/after_action_commitfor side effects.authorizegets the payload, and no row. The object thatcreatereturns is the subject of the action: the save adds it, flushes, refreshes it, and the hooks get it asnew. Call this from a custom create route, and from insideshared_write_action_commit()to share one commit with other writes; it then returns after the save, before the commit.- Raises:
TypeError –
createreturnedNone.
- async handle_update(id: IdT | ColumnElement[bool], data: UpdateSchemaT) ModelT#
Update handler: scoped load, then
updatein the commit bracket.You cannot override it, as with
handle_create():updatereceives the loaded object, so the load, the 404,authorizeand the reference check stay here.oldis the snapshot of the loaded row, andnewis the object thatupdatereturns, after the save. Insideshared_write_action_commit()it returns before the commit.- Raises:
TypeError –
updatereturnedNone.
- async handle_delete(id: IdT | ColumnElement[bool]) None#
Delete handler: scoped load, then
deletein the commit bracket.You cannot override it, as with
handle_create(). The loaded row is the subject. After a hard delete, the hooks getnew=None. A soft delete flips a timestamp indeleteand keeps the row, so the hooks get the row asnew. An off-request follow-up runs inafter_action_commit. Insideshared_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_manyaddsauthorize. The statement isselect(), thenapply_list_params(). A paginated view also runscount()fortotal_count; a view without pagination returns every matching row withtotal_count=None. Overrideapply_list_paramsto filter, sort or page in another way, andto_single_responseto add a value to each row.- Parameters:
list_params – the list params (filter, sort, page) as the endpoint receives them. A
QueryParamsor a mapping goes throughlist_params_schemafirst, as on the list route.scope – a clause that replaces the view scope for this read;
fr.clauses.UNSCOPEDreads unscoped.where – a SQLAlchemy boolean expression or a clause that narrows this read inside the scope.
- Raises:
TypeError –
whereis 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
idnames, through the scope, or the exception ofnot_found().You cannot override it. It is auth-free:
handle_get_oneaddsauthorize; a write action calls this directly and gates its own action. The statement isselect()withwhere_id(), so a row outside the scope is a 404 for every caller. Overridewhere_idto find the row by another key, andnot_foundto 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; onlyscope=replaces it.scope – a clause that replaces the view scope for this read;
fr.clauses.UNSCOPEDreads unscoped.
- Raises:
fastapi_restly.exc.NotFound – no row matches inside the scope, or the exception that
not_foundreturns.sqlalchemy.exc.MultipleResultsFound – more than one row matches; an ambiguous key is a bug in the criterion.
TypeError –
idis a Python bool (a comparison on a loaded object, which would render asWHERE true), an uncalled clause (a scope, not a row identity), or an expression on a table that the query does not select from; orwhere_idornot_foundreturned a value of the wrong kind.
- async create(data: CreateSchemaT) ModelT#
Build a new object from
dataand return it.Auth-free, flush-free and commit-free:
handle_createchecks the references before this method, and saves and commits after it. The default isfr.objects.async_make_new_objectwith 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): callsuper().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. Callawait self.session.flush()when you need the id inside this method. A direct call, outsidehandle_create, writes nothing.
- async update(obj: ModelT, data: UpdateSchemaT) ModelT#
Apply
datato the loadedobjand return it.Auth-free, flush-free and commit-free:
handle_updateloadsobjthroughget_one, gates, checks the references, and saves and commits after this method. The default isfr.objects.async_update_object. Override to check the stored row first, or to change the object aftersuper().update(). As increate, nothing is written before the save, and a direct call writes nothing.
- async delete(obj: ModelT) None#
Mark
objfor deletion. Does not flush or commit:handle_deletedoes.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 isfr.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 withawait. Override for list params of your own; the common case is driven by configuration. AQueryParamsor a mapping goes throughlist_params_schemafirst, as on the list route. In aQueryParams, a key that the route reads is left out. Any other key that the list params do not have raisesRequestValidationError, as on the list route (seeunknown_query_params).
- async apply_filters(stmt: Select, list_params: Any) Select#
Apply the filters of
list_paramstostmt, 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 callsauthorize()and starts fromselect(), which applies the scope.apply_list_params()calls this method first. AQueryParamsor a mapping goes throughlist_params_schemafirst, as on the list route. In aQueryParams, a key that the route reads is left out. Any other key that the list params do not have raisesRequestValidationError, as on the list route (seeunknown_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
stmtselects, 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 ajsoncolumn works on PostgreSQL, and the subquery of acolumn_propertydoes not run for every row. Astmtthat 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.objanddataareNone.get_one: after the scoped load.objis the row.create:objisNone, anddatais the request body.update: after the scoped load.objis the row, anddatais the request body.delete: after the scoped load.objis the row.every
write_action():objis its row, orNonefor a new object or for no single row.datais itsdata.
Override it to enforce a policy: raise
fr.exc.Forbiddenorfr.exc.NotFoundto 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.
oldis 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).
oldenables dirty detection (“notify only if the status changed”).For external effects only: the write is already durable, so mutating
newor the database here is NOT persisted. A mutation tonewalso leaks into this request’s response (which serializesnewafter this hook) while being silently discarded from storage. Do the mutation in the business method orbefore_action_commitinstead.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:
AsyncRestViewAsyncRestView 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 inscope, and the list params inapply_list_params. Restly builds the response withto_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(), thensortandrange.
- async apply_filters(stmt: Select, list_params: Any) Select#
Apply the react-admin
filtertostmt, without the sort and the range.
- async put(id: IDType, data: ViewUpdate) ViewResponse#
PUT /{id}endpoint method, for react-admin’supdate. It runs the same steps asPATCH:handle_update(), with the view’supdate_schemabody. Anupdateoverride changes both routes. Replace this method to givePUTits 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_schemaandmodelbyderive_list_params_schema(). Any route method on the view that declares alist_paramsparameter takes it: typed for FastAPI and OpenAPI, and guarded against unknown keys likeGET /, 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_sizeandmax_page_sizeapply: the implicit page size when norangeparameter is sent, and the most rows onerangemay ask for. Override per view.
- list_response_schema: ClassVar[Any]#
A react-admin list is a JSON array, without an envelope.
- to_list_response(list_result: ListResult[Any]) Response#
Build the react-admin list response: a JSON array with a
Content-Rangeheader.
- class fastapi_restly.views.ReactAdminView#
Bases:
RestViewRestView 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 inscope, and the list params inapply_list_params. Restly builds the response withto_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(), thensortandrange.
- apply_filters(stmt: Select, list_params: Any) Select#
Apply the react-admin
filtertostmt, without the sort and the range.
- put(id: IDType, data: ViewUpdate) ViewResponse#
PUT /{id}endpoint method, for react-admin’supdate. It runs the same steps asPATCH:handle_update(), with the view’supdate_schemabody. Anupdateoverride changes both routes. Replace this method to givePUTits 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_schemaandmodelbyderive_list_params_schema(). Any route method on the view that declares alist_paramsparameter takes it: typed for FastAPI and OpenAPI, and guarded against unknown keys likeGET /, 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_sizeandmax_page_sizeapply: the implicit page size when norangeparameter is sent, and the most rows onerangemay ask for. Override per view.
- list_response_schema: ClassVar[Any]#
A react-admin list is a JSON array, without an envelope.
- to_list_response(list_result: ListResult[Any]) Response#
Build the react-admin list response: a JSON array with a
Content-Rangeheader.
- 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:
BaseModelThe list params of a react-admin view:
sort,rangeandfilter.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:sortas("name", "DESC"),rangeas(0, 24)andfilteras a dict. JSON that does not have this shape gets a422that 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").Nonewhen the request has no sort.
- class fastapi_restly.views.BaseRestView#
Bases:
ViewThe part that
RestViewandAsyncRestViewshare: the settings, the read statement and the response methods.It has no routes, no handlers and no business methods. Those are on
RestViewandAsyncRestView, 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_schemaandupdate_schemafrom it. When a view sets none, Restly generates it frommodelwithderive_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 itsWriteOnlyfields, 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 declaresViewListResponsesend. When a view sets none, Restly builds it withderive_list_response_schema(): the envelope of the view’spagination, 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 asdata,total_count,page,page_sizeandtotal_pages. A view that replacesget_many_endpointcan set any type here.
- create_schema: ClassVar[type[BaseModel]]#
The class of the
POSTbody. When a view sets none, Restly builds it from the main schema without itsReadOnlyfields 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
PATCHbody. When a view sets none, Restly builds it from the main schema without itsReadOnlyfields 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
RestlyConfigurationErrorwhen 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 declareddefault_scope;fr.clauses.UNSCOPEDreads unscoped despite that default. Declaring a scope replaces the default, it does not stack on it; compose the replacement from the same leaves (ItemClauses.trashedcontaining the tenant clausevisiblecontains). A rule that must hold under every scope is a session-levelwith_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 getsint. Set a type to override it. Built-in item routes use Starlette’sintoruuidpath 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’sextrasetting. The same rule applies to aQueryParamsthat a method gets as list params.
- pagination: ClassVar[Pagination | None] = NumberedPagination()#
How list endpoints paginate. The default
NumberedPaginationtakespage/page_sizequery parameters, runs the count query, and wraps the list in itsenvelope(NumberedEnvelope:dataplustotal_count/page/page_size/total_pages). AnOffsetPaginationdoes the same withlimit/offsetquery parameters (OffsetEnvelope:dataplustotal_count/limit/offset). ANoPaginationreturns every matching row with no count, in itsenvelope;Noneis short forNoPagination(), a plainEnvelope(dataonly). A view inherits it, so a project base view sets it once; a view that differs changes one setting withreplace()on the shared settings. For a shape no envelope model can express, such as a header, replaceget_many_endpointwith a matchingresponse_model(seeAsyncReactAdminView).
- 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 oncreated_atwith a suffix, and"vendor.*"is every key on the fields ofvendor. 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 removesname__in.
- include_sort_keys: ClassVar[tuple[str, ...]] = ('*',)#
The keys that
sortaccepts: the Python name of a field, such as"name"or"vendor.name", or a pattern as ininclude_filters. The default,("*",), is the resource’s own fields. A sort key never goes through a to-many relationship. With(), the list has nosortparameter.
- 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 ofresponse_schemathat a sort key could have, butinclude_sort_keysdoes 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.Noneleaves 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_schemaandmodelbyderive_list_params_schema(). Any route method on the view that declares alist_paramsparameter takes it: typed for FastAPI and OpenAPI, and guarded against unknown keys likeGET /, 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 asession.commit()in the action, and an error undoes all of its work.Falseallows 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, andafter_action_commitdoes 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 outermostshared_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.Requestof the current request, which Restly sets for each request. Afterinclude_view(), a view that you create yourself must getrequest=(Noneoutside a request) andsession=.
- select(*, scope: WhereClause | None = None) Select#
The statement of the view’s rows:
select(model), the scope, andget_loader_options().get_oneandget_manystart 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: setscopeto change the rows, and overrideget_loader_options()to change the loads.- Parameters:
scope – a clause that replaces the view scope for this statement;
fr.clauses.UNSCOPEDreads 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,PATCHandDELETE /{id}, andself.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 returnand_(...). The expression must name the view’s model, not another table, and it runs no query, so define it withdef, 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_oneraises what this returns, so an override can change the text or the status, such as410for a row that was deleted. On an async view it may beasync def, and Restly awaits it.idis the id from the path, orNonewhen a route loaded by an expression, such ashandle_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 thatresponse_schemanames.select()applies them, soget_one,get_manyand 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 aquery_expressionthroughwith_expression(...). Add tosuper().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 asschema. Only the fields of the response schema go out. Restly copies the values of an instance of a subclass of the response schema, and ofschemawhen 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
schemafrom the ORM object also reads the relationships of its WriteOnly fields. On an async view that fails withMissingGreenlet: add them inget_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.
passwordbacked by apassword_hashcolumn) doesn’t fail response validation. It validates in lax mode, also for a strict class, so a strictfloatfield 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
envelopeof the view’spagination: aNumberedEnvelope(dataplustotal_count/page/page_size/total_pages), anOffsetEnvelope(dataplustotal_count/limit/offset), or anEnvelope(dataonly) for a view without pagination. To change the shape, setlist_response_schemaor the pagination’senvelope. A list type, such aslist[UserSummary], gives a list without the page values. For aContent-Rangeheader, seeAsyncReactAdminView: it overrides this method and setslist_response_schemato 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 asoldtobefore_action_commitandafter_action_committo 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 whatoldholds, 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_manybefore HTTP response formatting.total_countisNonefor a list without pagination, which does not run the count query.list_paramsholds the list params thatget_manyreceived, soBaseRestView.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
Nonefor a list without pagination. A paginated list response sendsNoneas0.
- list_params: Any = None#
The list params that
get_manyreceived. 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:
PaginationPage-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 withreplace():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 )
envelopeis 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 fromdata,total_count,page,page_sizeandtotal_pages. Leave a field out to drop it from the response, and rename one with analiasor analias_generator. Amodel_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 defaultextrasetting: Restly passes it every page value and it keeps the fields it declares.- max_page: int | None = None#
The largest page number a client may ask for. A larger one returns 422.
Nonesets no limit of its own: then only a page whose offset is above2**63 - 1returns 422.
- envelope: type[BaseModel] = NumberedEnvelope#
The list response model.
NumberedEnvelopeby 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:
PaginationLimit and offset pagination:
?limit=50&offset=100.Set an instance as a view’s
pagination. It works asNumberedPaginationdoes: views inherit it, andreplace()changes one setting. For a client that saysskip:class ItemView(fr.AsyncRestView): pagination = fr.OffsetPagination( offset_query_param="skip", default_limit=20, max_limit=100 )
envelopeworks as forNumberedPagination, and Restly fills it by name fromdata,total_count,limitandoffset. The names in the JSON do not follow the names in the URL: to sendskipin the response too, give the field analias.- max_offset: int | None = None#
The largest
offseta client may ask for. A larger one returns 422.Nonesets no limit of its own: then only an offset above2**63 - 1returns 422.
- envelope: type[BaseModel] = OffsetEnvelope#
The list response model.
OffsetEnvelopeby default.
- class fastapi_restly.views.NoPagination(*, envelope: type[BaseModel] = Envelope)#
Bases:
PaginationNo pagination: a list returns every matching row and runs no count query.
pagination = Noneis the short form ofNoPagination(). 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)
envelopeworks as forNumberedPagination, and Restly fills it by name fromdataandtotal_count, the number of rows. A genericpydantic.RootModelover the items whose before-validator returnsdatamakes the list a bare JSON array.
- class fastapi_restly.views.Pagination(*, envelope: type[BaseModel] = Envelope)#
Bases:
ABCThe base class of the pagination settings:
NumberedPagination,OffsetPaginationandNoPagination.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.
- class fastapi_restly.views.Envelope(*, data: list[DataT])#
Bases:
BaseModelList response wrapper:
{"data": [...]}.The default
envelopeofNoPagination, for a view that returns every row. A paginated view uses its pagination’senvelope:NumberedEnvelopeorOffsetEnvelopeby default.
- class fastapi_restly.views.NumberedEnvelope(*, data: list[DataT], total_count: int, page: int, page_size: int, total_pages: int)#
Bases:
EnvelopeList response with page numbers:
dataplus pagination metadata.The default
envelopeofNumberedPagination.
- class fastapi_restly.views.OffsetEnvelope(*, data: list[DataT], total_count: int, limit: int, offset: int)#
Bases:
EnvelopeList response with a limit and an offset:
dataplus pagination metadata.The default
envelopeofOffsetPagination.
- class fastapi_restly.views.Action#
The names of the five CRUD actions: the
actionthatauthorizegets. A write, such asCREATEor the action of awrite_actionblock, also passes it tobefore_action_commitandafter_action_commit. A read,GET_MANYorGET_ONE, has no commit, so it reaches onlyauthorize.Each view has a class
Actionthat 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
Actionclass has only actions. An action has an UPPER_CASE name, and its value is that name in lower case.write_actiontakes only a value that the view’sActiondeclares. A view with base classes that declare actions, such as a mixin, inherits from theirActionclasses 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:
Nonefor the view’s own, a clause that replaces it for that read, orfr.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
RestVieworAsyncRestView, which extendViewwith CRUD scaffolding. UseViewdirectly 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-itemsgivesOrder 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
Noneis 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_schemaalso takes a list type. A route can get any type that FastAPI accepts. The function can use a marker in what it returns, as inData[ViewResponse].- Parameters:
fn – The function. It gets the view class and returns the type.
- 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’sdefault_scopewhen the view declares none, andfr.clauses.UNSCOPEDwhen 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, neverNone, 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_oneandget_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:
RestlyConfigurationError – if the declared scope is not a clause.
TypeError – if
targetis neither a view nor a mapped model.
- 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_viewagain 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 gets422. 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
Nonefor 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 beasync def.The key is a name of your own, such as
popular, or a field and an operator, such asname__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 asvendor.name. The key is the key in the URL, so a field goes by its alias when it has one. The key settings, such asexclude_filters, use Python names.The key is always on:
include_filtersandexclude_filterschoose among the generated keys only. A subclass drops the key by setting the method name toNone.- Raises:
RestlyConfigurationError –
keyis 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’sAPIRouter.add_api_route().pathreplaces the path of the route.Each argument replaces the one of the inherited route.
dependenciesandresponsesadd up, as they do on a view.dependenciesrun base first.responsesadd up per status code, and a status code set toNoneis 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_modeland the otherresponse_model_*arguments raiseRestlyConfigurationError. To change the response of the view, setresponse_schemaorlist_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
RestlyConfigurationErrorwhen 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.
pathandapi_route_kwargsgo to FastAPI’sAPIRouter.add_api_route()wheninclude_view()registers the view. Withoutmethods=, the route is aGETwith status 200, as in FastAPI.get(),post(),patch(),put()anddelete()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}forintand{id:uuid}forUUID.
- 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.