Query API#
fastapi_restly.query implements list-endpoint filtering, sorting, and
pagination: derive_list_params_schema() derives the list params, a model
of the URL parameters, from the view’s response schema and its model, and
apply_list_params() applies validated list params to a SQLAlchemy select.
For list params of your own, PagedListParams and OffsetListParams
give the page fields of the view’s pagination, FilterKey and SortKey find the field and the
column of one key, and order_by_primary_key() orders by the primary key
last; see Write the list params yourself and Filter and sort on the fields of the response.
The view classes call the two functions for you. Call them yourself only in
a custom endpoint that needs the same list params, and pass validated list
params, not raw QueryParams. Pass the view’s settings to
derive_list_params_schema(): pagination=self.pagination, and
include_filters, exclude_filters, include_sort_keys,
exclude_sort_keys, sort_query_param and default_sort.
apply_list_params() takes (stmt, list_params, model, response_schema),
in the same order as the view method apply_list_params(stmt, list_params),
and the view’s sort_nulls=self.sort_nulls.
Pass the view’s self.response_schema, not self.schema: the list params
follow the response schema.
- fastapi_restly.query.DEFAULT_PAGE_SIZE = 50#
The
page_sizeorlimitof a list when the client does not send one. A bounded default keeps a forgotten parameter from returning an entire table. Override per view throughdefault_page_sizeordefault_limit; to return every row, set the view’spaginationtoNoneinstead of removing the cap.
- fastapi_restly.query.MAX_PAGE_SIZE = 1000#
The largest
page_sizeorlimitthat a list accepts. A larger value returns 422. Override per view throughmax_page_sizeormax_limit.
- class fastapi_restly.query.FilterKey(model: type[Any], response_schema: type[BaseModel], key: str)#
One filter key of list params of your own: the field of the response schema that the client’s key names, and the column of the model.
key = fr.query.FilterKey(self.model, self.response_schema, "status") stmt = stmt.where(key.column == key.parse("active"))
The key is the name of a field, or its alias when the field has one, as in the generated filters. The model has an attribute with the name of the field that is one value in SQL: a column, a
column_property, or a hybrid property with an SQL expression. A hybrid property that is plain Python, such asself.deleted_at is not None, is no filter key. Neither is a field that a response never shows: aWriteOnlyfield, one withexclude=True, or one of Pydantic’s secret types. A filter on it would let a client find out its value. Restly cannot see a value that a serializer hides; type such a field as a subclass ofpydantic.Secretinstead. A key with a dot, such asvendor.name, needs a join, so it is unknown here. The react-admin views use this class for theirfilter.- Parameters:
model – The model of the rows, such as the view’s
model.response_schema – The response schema. A view passes its
response_schema, so a client can filter only on a field of that class.key – The key, as the client sends it.
- Raises:
fastapi_restly.exc.BadQueryParam –
Unknown filter key.
- column: QueryableAttribute[Any]#
The attribute of the model that the key filters, such as
Item.status.
- parse(value: Any) Any#
valueas the column takes it, for a condition such askey.column == key.parse(value).The value goes through the validation of the field, as in the generated filters, so the validators of the field run too, and its bounds, such as
gt, do not count. The validators get only this field, soinfo.datais{}; see Filter values go through the field’s validation. The value can be text from a URL or a value from JSON, and a number becomes text for a text field.NonestaysNonewhen the field allows it, sokey.column == NonegivesIS NULL. A value that a validator turns intoNone, such as empty text, fails: the client did not ask for NULL. A reference, such asIDRef[User], gives its id. A field of typeAny, such as theidoffr.IDSchema, and the id of a reference get the Python type of the column, such as aUUIDfrom its text. A column of SQLAlchemy’sEnumtype takes only its labels. A field on a JSON column takes onlyNone, as the generated filters have only__isnullfor it: the column holds JSON text, so SQL cannot compare it with a value. A time gets the form of its column; see Keep times in UTC. A number must fit its integer column, and text must hold no NUL character; see Column validation. The length of text is not checked.- Raises:
fastapi_restly.exc.BadQueryParam –
Invalid filter value, with the reason.
- class fastapi_restly.query.OffsetListParams(*, limit: Annotated[int, Ge(ge=1), Le(le=1000)] = 50, offset: Annotated[int, Ge(ge=0), Le(le=9223372036854775807)] = 0)#
Bases:
BaseModelThe base of list params of your own with a limit and an offset: the fields
limitandoffset.class ItemSearch(fr.query.OffsetListParams): q: str | None = None
When a view with a
OffsetPaginationregisters, Restly gives the two fields the settings of the view’spagination: their names in the URL, such asskipforoffset_query_param="skip", the default limit and the bounds. So each view gets its own limits from one class. Your code readslist_params.limitandlist_params.offset, also when the URL names them otherwise.Restly’s own
apply_list_paramsapplies the limit and the offset. An override of it applies them itself; see Write the list params yourself. A view with another pagination does not take these list params, and a view fails when it registers if a subclass declares one of the two fields again: set the default and the bounds on the pagination. Outside a view, the fields keep their defaults:offset0, andlimitDEFAULT_PAGE_SIZE, at mostMAX_PAGE_SIZE.
- class fastapi_restly.query.PagedListParams(*, page: Annotated[int, Ge(ge=1)] = 1, page_size: Annotated[int, Ge(ge=1), Le(le=1000)] = 50)#
Bases:
BaseModelThe base of list params of your own with pages: the fields
pageandpage_size.class ItemSearch(fr.query.PagedListParams): q: str | None = None
When a view with a
NumberedPaginationregisters, Restly gives the two fields the settings of the view’spagination: their names in the URL, such assizeforpage_size_query_param="size", the default page size, the bounds, and the check that the offset of the page fits in the database. So each view gets its own pages from one class. Your code readslist_params.pageandlist_params.page_size, also when the URL names them otherwise.Restly’s own
apply_list_paramsapplies the page. An override of it applies the page itself; see Write the list params yourself. A view with another pagination does not take these list params, and a view fails when it registers if a subclass declares one of the two fields again: set the default and the bounds on the pagination. Outside a view, the fields keep their defaults:page1, andpage_sizeDEFAULT_PAGE_SIZE, at mostMAX_PAGE_SIZE.
- class fastapi_restly.query.SortKey(model: type[Any], response_schema: type[BaseModel], key: str)#
One sort key of list params of your own: the field of the response schema that the client’s key names, and the column of the model.
key = fr.query.SortKey(self.model, self.response_schema, "name") stmt = stmt.order_by(key.term(descending=True, sort_nulls=self.sort_nulls))
It finds the field and the column as
FilterKeydoes. A field that a response never shows is no sort key either: the order of the rows would let a client find out its value. Neither is a field that holds adict, alistor a nested model, or a field on a JSON column, as in the generated list params: a document has no order that a client means, and PostgreSQL’sjsontype has none at all. The react-admin views use this class for theirsort.- Parameters:
model – The model of the rows, such as the view’s
model.response_schema – The response schema. A view passes its
response_schema, so a client can sort only on a field of that class.key – The key, as the client sends it.
- Raises:
fastapi_restly.exc.BadQueryParam –
Unknown sort key.
- column: QueryableAttribute[Any]#
The attribute of the model that the key sorts on, such as
Item.name.
- term(*, descending: bool = False, sort_nulls: Literal['first', 'last'] | None = 'last') ColumnElement[Any]#
The term for
order_by(). Order by the primary key after it, withorder_by_primary_key(), so that a row never moves to another page.- Parameters:
descending – Sort from the highest value to the lowest.
sort_nulls – Where the NULLs go:
"last"(the default) or"first"in both directions, orNonefor where the database puts them. A view passes itssort_nulls.
- fastapi_restly.query.SortNulls#
Where a sort puts NULLs: first or last in both directions, or where the database puts them.
- fastapi_restly.query.apply_list_params(stmt: Select, list_params: BaseModel | QueryParams, model: type[Any], response_schema: type[BaseModel], *, pagination: Pagination | None = ..., sort_nulls: Literal['first', 'last'] | None = 'last') Select#
Apply pagination, sorting, and filtering to
stmtusing validated list params.list_paramsis normally an instance of the model returned byderive_list_params_schema(). The default list endpoints pass a validated instance, so the page, the page size and each filter value have passed their fields. This function uses the values of such an instance as they are. So a value that your code sets without validation, as withmodel_copy(update=...), must have the type of its field:True, not"true". Other list params, such as a dict or a model of your own, go through the validation of each field here.response_schemadecides the fields a client can filter and sort on. A view passes its response schema.The arguments match the view method
apply_list_params(), which calls this function with the view’s model, response schema and pagination.With list params from
derive_list_params_schema(), the sort parameter has the name that the model was created with, and accepts only its sort keys. With rawQueryParamsor a hand-written model, the sort parameter issort. List params with a value for a view’s own filter key, fromlist_filter(), raiseValueError: only the view can apply them. Use the view’sapply_list_params.A raw
QueryParamsis also accepted for callers that build the query parameters programmatically. It skips the list params model, so nothing checks the bounds of the page, such asmax_page_sizeormax_limit: the caller checks them. Each filter value still goes through the validation of its field. Every filter key thatderive_list_params_schema()can generate works, also a dotted one.paginationnames the page parameters to read, and says how the page applies. By default it is the pagination that the list params were created with, byderive_list_params_schema()or by a view.OffsetListParamsoutside a view readlimitandoffset. RawQueryParamsand other hand-written models readpageandpage_size.A
NoPaginationorNoneapplies noLIMIT/OFFSET. With page numbers, a missing page-size key also applies neither. With an offset, a missing limit applies noLIMIT, and the offset still applies.sort_nullssays where the sort puts NULLs:"last"(the default) or"first"in both directions, orNonefor where the database puts them. Without a sort parameter, the sort is thedefault_sortthat the list params were created with.Examples:
# Pagination page=2&page_size=50 limit=50&offset=50 # Sorting sort=name,-created_at # Filtering name=Bob&status=active&created_at__gte=2024-01-01 # Search in text (text columns) name__icontains=John&email__icontains=example
- fastapi_restly.query.derive_list_params_schema(response_schema: type[BaseModel], model: type[Any], *, pagination: Pagination | None = NumberedPagination(), include_filters: Iterable[str] = ('*',), exclude_filters: Iterable[str] = (), include_sort_keys: Iterable[str] = ('*',), exclude_sort_keys: Iterable[str] = (), sort_query_param: str = 'sort', default_sort: str | None = None) type[BaseModel]#
Build the list params: a Pydantic model that describes and validates the URL query parameters of a list endpoint. A view keeps it in
list_params_schema.The generated model accepts pagination (
pageandpage_size, orlimitandoffset), sorting (sort), and filters. Each field ofresponse_schemathat maps to a column ofmodelgives filter keys, and its type decides which ones. Every such field gives the plain key and the keys with the suffixes__in,__neand__not_in. A column that can be NULL also gives__isnull, and so does each dotted key, because a related row can be missing. A type with an order, such as a number, a date or an int enum, also gives__gte,__lte,__gtand__lt, unless the column has SQLAlchemy’sEnumtype, which holds labels. A text column gives__icontains, and range keys only for a field of typedate.A field that does not map to a column, such as a relationship, gives no keys. A WriteOnly field gives none either, because a filter on it would let a client find out its value. A name with
.or__gives none, because a key could not be read back. A field whose type is a collection (dict/list, e.g. aJSONorARRAYcolumn) gives only__isnull: a value from the URL cannot become a collection. A field on a JSON column gives only__isnulltoo, also when it holds one value, such as astr: the database compares the JSON text, not the value. A field of a nested schema gives dotted keys, such asvendor.name.The model forbids a key that it does not have, so a route of your own answers
422for it. A view passes on only the keys that it knows when itsunknown_query_paramsis"ignore".Each key has the type of the field and its validators, without its bounds, such as
gt: a filter compares a value, and does not store it. Only__inand__not_intake several values, separated by commas or from a repeated key.The four key settings choose which of these keys the model has. Each entry is a key with the Python name of its field, also for a field with an alias, or a pattern. An entry with the name in the URL of such a field raises an error.
*in a pattern matches any characters except., so it stays within one level. By default the model has the keys of the resource’s own fields, and no dotted keys. An entry that matches no key raises an error.With a
pagination(the default ispageandpage_size), its two query parameters are added under its names and validated by Pydantic with bounds. With aNumberedPagination, the page is at least 1 and at mostmax_pagewhen set, and the page size is from 1 tomax_page_size. With anOffsetPagination, the limit is from 1 tomax_limit, and the offset is at least 0 and at mostmax_offsetwhen set. The resulting SQL offset must also fit in a signed 64-bit integer. Out-of-range values produce a standard 422 response from FastAPI. With aNoPaginationorNone, no pagination parameters are emitted at all – the endpoint returns every matching row – while sorting and filtering stay available.- Parameters:
response_schema – The response schema whose fields decide the available filter parameters. A view passes its
response_schema, so a client can filter only on a field of that class.model – The SQLAlchemy model the list endpoint queries. Used to verify each field resolves to a filterable column; non-column fields are omitted from the generated params.
pagination – The view’s pagination settings. A
NoPaginationorNoneis an unpaginated view, which returns the full result set.include_filters – The filter keys to keep.
("*", "*.*")keeps the own keys and the dotted keys one level down, and()keeps none. Each entry must match a key, so"*.*"needs a nested schema.exclude_filters – The filter keys to remove, after
include_filters. A name without a suffix removes the whole field: the plain key and each key with a suffix.include_sort_keys – The keys that
sortaccepts. A sort key has no suffix, and never goes through a to-many relationship. With(), the model has nosort.exclude_sort_keys – The sort keys to remove, after
include_sort_keys.sort_query_param – The name of the sort parameter, such as
"order_by".default_sort – The sort when the request has none, 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. A key must be a field that a sort key could have, butinclude_sort_keysdoes not have to keep it.
- Raises:
fastapi_restly.exc.RestlyConfigurationError – An entry of a key setting matches no key, matches only names in the URL, or is not a key or pattern. The sort parameter has the name of a page parameter. A key of
default_sortis not a field to sort on, or appears twice.
- fastapi_restly.query.order_by_primary_key(stmt: Select, model: type[Any], *, sorted_on: Iterable[Any] = ()) Select#
stmtordered by the primary key ofmodellast, after the order that it has.Rows with the same sort value come back in any order, so a row can move to another page between two requests. The primary key makes the order unique. The generated list params add it themselves. List params of your own call this function, as the react-admin views do:
stmt = stmt.order_by(key.term(descending=True)) stmt = fr.query.order_by_primary_key( stmt, self.model, sorted_on=[key.column] )
A key with several columns gets each column, in the order of the model.
- Parameters:
sorted_on – The columns that
stmtis ordered by already, such as thecolumnof aSortKey. A key column among them does not come again: SQL Server refuses a column that is twice inORDER BY.
See also
Filtering, Sorting & Pagination documents the list params that these helpers build and apply: filter, sort and pagination.