Part 4: Lists: filters, search, ordering, pages
A list endpoint is rarely read whole. Clients filter it, search it, sort
it and read it page by page. In DRF you would add django-filter, a
SearchFilter, an OrderingFilter and a pagination class. In rind the
four are part of the resource.
Filters
The generated filters.rs holds an empty filterset: a struct whose
fields are query parameters. Let’s fill it:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/filters.rs
use catalog_models::Book;
use rind::FilterSet;
/// What the list of books can be filtered by.
#[derive(Debug, Default, FilterSet)]
#[filterset(model = Book)]
pub struct BookFilters {
/// `?author=2`: the books of one author.
#[filter(path = Book::author_id())]
pub author: Option<i64>,
/// `?published_after=1970`
#[filter(path = Book::year(), lookup = gt)]
pub published_after: Option<i32>,
/// `?published_before=1970`
#[filter(path = Book::year(), lookup = lt)]
pub published_before: Option<i32>,
}
}
Each field is one parameter. Its name is the name of the parameter, its
type says how the value is read, path is the column it filters on, and
lookup the comparison: eq by default, and gt, lt, ge, le,
ne, icontains… (the Filters chapter lists them). It
is django-filter’s NumberFilter(field_name="year", lookup_expr="gt").
The doc comments (///) are not only for you: they go into the OpenAPI
description of the parameter.
curl 'localhost:8080/books?include=author_details&author=2'
{
"parameters": {…},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 2, "pages": 1},
"results": [
{"id": 3, "title": "A Wizard of Earthsea", "year": 1968, "author": 2,
"author_details": {"id": 2, "name": "Ursula K. Le Guin"}},
{"id": 2, "title": "The Dispossessed", "year": 1974, "author": 2,
"author_details": {"id": 2, "name": "Ursula K. Le Guin"}}
]
}
A value of the wrong type is a 400 that names the parameter:
curl 'localhost:8080/books?author=abc'
{"author":["Enter a number."]}
As with django-filter, an empty value and an unknown parameter are ignored.
Search
?search= looks for words in some fields: DRF’s search_fields. The
resource says which fields, and how:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/views.rs
#[derive(Resource)]
#[resource(model = Book, path = "books", /* … as before … */)]
#[rule(anyone)]
#[search(Book::title(), unaccent)]
#[search(Book::author().name(), unaccent)]
#[ordering(by(id, title, year), default("title"))]
pub struct BookResource;
}
Book::author().name() follows the foreign key: a book is found by the
name of its author, as "author__name" does in Django. unaccent
ignores case and accents, so guin finds “Le Guin” and eric would find
“Éric”.
unaccent uses a PostgreSQL extension of the same name. The domain
declares that it needs it, in its models crate:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-models/src/lib.rs
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("catalog", schema()).extension("unaccent")
}
}
and a migration creates it:
rind make --name unaccent
rind migrate
catalog 0002_unaccent
extension unaccent
-- crates/catalog/catalog-models/migrations/0002_unaccent.sql
CREATE EXTENSION IF NOT EXISTS "unaccent";
Watch out: if you forget the extension, the code compiles and
rind checkpasses, but every search answers500and the server’s log saysfunction unaccent(character varying) does not exist.
curl 'localhost:8080/books?search=guin&fields=title'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 3, "title": "A Wizard of Earthsea"},
{"id": 2, "title": "The Dispossessed"}
]
}
Several words must all match (?search=le guin), and a quoted phrase is
one word, as in DRF.
Ordering
#[ordering(by(id, title, year), default("title"))] lists the names a
client may sort by, and the default order. It replaces both DRF’s
ordering_fields and Django’s Meta.ordering:
curl 'localhost:8080/books?published_after=1966&ordering=-year&fields=title,year'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 2, "title": "The Dispossessed", "year": 1974},
{"id": 3, "title": "A Wizard of Earthsea", "year": 1968}
]
}
-year sorts in descending order. A name that is not allowed is ignored,
and the default order applies.
rind always adds the primary key at the end of an ordering. Two books of the same year are then always in the same order, so a page never shows a book twice, and never skips one.
Pages
Every list is paginated. The default page has 100 objects; the client
chooses with page and page_size:
curl 'localhost:8080/books?page_size=2&page=2&fields=title'
{
"parameters": {"page": "page", "pagesize": "page_size"},
"nav": {"size": 2, "page": 2, "next": null, "prev": 1, "count": 3, "pages": 2},
"results": [{"id": 2, "title": "The Dispossessed"}]
}
nav.countis the number of objects after the filters and the search;nav.pagesthe number of pages.nav.nextandnav.prevare page numbers (not URLs, as in DRF), ornull.parameterstells the client the names of the two parameters.?page=lastis the last page. A page that does not exist answers the first page, not an error.
Coming from Django: the envelope is not DRF’s
{count, next, previous, results}. If you port an API whose clients expect another shape, see Answering as Django did.
Everything together
The parameters combine freely:
GET /books?search=dune&published_after=1960&ordering=-year&page_size=20&fields=title,author_details
rind runs this as one query for the page and one for the count, plus one for the nested authors: never one query per book.