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_size or limit of a list when the client does not send one. A bounded default keeps a forgotten parameter from returning an entire table. Override per view through default_page_size or default_limit; to return every row, set the view’s pagination to None instead of removing the cap.

fastapi_restly.query.MAX_PAGE_SIZE = 1000#

The largest page_size or limit that a list accepts. A larger value returns 422. Override per view through max_page_size or max_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 as self.deleted_at is not None, is no filter key. Neither is a field that a response never shows: a WriteOnly field, one with exclude=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 of pydantic.Secret instead. A key with a dot, such as vendor.name, needs a join, so it is unknown here. The react-admin views use this class for their filter.

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.

key: str#

The key, as the client sent it.

column: QueryableAttribute[Any]#

The attribute of the model that the key filters, such as Item.status.

parse(value: Any) → Any#

value as the column takes it, for a condition such as key.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, so info.data is {}; 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. None stays None when the field allows it, so key.column == None gives IS NULL. A value that a validator turns into None, such as empty text, fails: the client did not ask for NULL. A reference, such as IDRef[User], gives its id. A field of type Any, such as the id of fr.IDSchema, and the id of a reference get the Python type of the column, such as a UUID from its text. A column of SQLAlchemy’s Enum type takes only its labels. A field on a JSON column takes only None, as the generated filters have only __isnull for 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: BaseModel

The base of list params of your own with a limit and an offset: the fields limit and offset.

class ItemSearch(fr.query.OffsetListParams):
    q: str | None = None

When a view with a OffsetPagination registers, Restly gives the two fields the settings of the view’s pagination: their names in the URL, such as skip for offset_query_param="skip", the default limit and the bounds. So each view gets its own limits from one class. Your code reads list_params.limit and list_params.offset, also when the URL names them otherwise.

Restly’s own apply_list_params applies 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: offset 0, and limit DEFAULT_PAGE_SIZE, at most MAX_PAGE_SIZE.

limit: int#

The largest number of rows to return.

offset: int#

The number of rows to skip.

class fastapi_restly.query.PagedListParams(*, page: Annotated[int, Ge(ge=1)] = 1, page_size: Annotated[int, Ge(ge=1), Le(le=1000)] = 50)#

Bases: BaseModel

The base of list params of your own with pages: the fields page and page_size.

class ItemSearch(fr.query.PagedListParams):
    q: str | None = None

When a view with a NumberedPagination registers, Restly gives the two fields the settings of the view’s pagination: their names in the URL, such as size for page_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 reads list_params.page and list_params.page_size, also when the URL names them otherwise.

Restly’s own apply_list_params applies 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: page 1, and page_size DEFAULT_PAGE_SIZE, at most MAX_PAGE_SIZE.

page: int#

The page, from 1.

page_size: int#

The number of rows on a page.

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 FilterKey does. 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 a dict, a list or 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’s json type has none at all. The react-admin views use this class for their sort.

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.

key: str#

The key, as the client sent it.

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, with order_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, or None for where the database puts them. A view passes its sort_nulls.

fastapi_restly.query.SortNulls#

Where a sort puts NULLs: first or last in both directions, or where the database puts them.

alias of Literal[‘first’, ‘last’] | None

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 stmt using validated list params.

list_params is normally an instance of the model returned by derive_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 with model_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_schema decides 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 raw QueryParams or a hand-written model, the sort parameter is sort. List params with a value for a view’s own filter key, from list_filter(), raise ValueError: only the view can apply them. Use the view’s apply_list_params.

A raw QueryParams is 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 as max_page_size or max_limit: the caller checks them. Each filter value still goes through the validation of its field. Every filter key that derive_list_params_schema() can generate works, also a dotted one.

pagination names the page parameters to read, and says how the page applies. By default it is the pagination that the list params were created with, by derive_list_params_schema() or by a view. OffsetListParams outside a view read limit and offset. Raw QueryParams and other hand-written models read page and page_size.

A NoPagination or None applies no LIMIT/OFFSET. With page numbers, a missing page-size key also applies neither. With an offset, a missing limit applies no LIMIT, and the offset still applies.

sort_nulls says where the sort puts NULLs: "last" (the default) or "first" in both directions, or None for where the database puts them. Without a sort parameter, the sort is the default_sort that 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 (page and page_size, or limit and offset), sorting (sort), and filters. Each field of response_schema that maps to a column of model gives filter keys, and its type decides which ones. Every such field gives the plain key and the keys with the suffixes __in, __ne and __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, __gt and __lt, unless the column has SQLAlchemy’s Enum type, which holds labels. A text column gives __icontains, and range keys only for a field of type date.

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. a JSON or ARRAY column) gives only __isnull: a value from the URL cannot become a collection. A field on a JSON column gives only __isnull too, also when it holds one value, such as a str: the database compares the JSON text, not the value. A field of a nested schema gives dotted keys, such as vendor.name.

The model forbids a key that it does not have, so a route of your own answers 422 for it. A view passes on only the keys that it knows when its unknown_query_params is "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 __in and __not_in take 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 is page and page_size), its two query parameters are added under its names and validated by Pydantic with bounds. With a NumberedPagination, the page is at least 1 and at most max_page when set, and the page size is from 1 to max_page_size. With an OffsetPagination, the limit is from 1 to max_limit, and the offset is at least 0 and at most max_offset when 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 a NoPagination or None, 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 NoPagination or None is 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 sort accepts. A sort key has no suffix, and never goes through a to-many relationship. With (), the model has no sort.

  • 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, but include_sort_keys does 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_sort is 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#

stmt ordered by the primary key of model last, 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 stmt is ordered by already, such as the column of a SortKey. A key column among them does not come again: SQL Server refuses a column that is twice in ORDER BY.

See also

Filtering, Sorting & Pagination documents the list params that these helpers build and apply: filter, sort and pagination.