Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Parameters: the other query parameters

Most of a query string is read by rind itself, or by what you derive: the filters, search, ordering, page and page_size, the field selection (fields, omit, include), and an action’s #[query] arguments. But a request sometimes says other things:

  • “really delete it” (?confirm=yes),
  • “show the hidden ones too” (?show_retired=true),
  • “do not narrow this nested list” (?filter_wagons=0).

These values are not filters: they do not narrow a list. In Django, a view would read them with self.request.query_params.get("confirm"). In rind, they are typed parameters: you declare them as the fields of a struct, and the code reads the struct.

A first example

When a client deletes a station, the sample only tries the deletion and answers with what would be deleted. It deletes for real only when the request says ?confirm=yes. The parameter is a struct:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
use rind::{ParamValue, Parameters};

/// What a deletion of a station reads.
#[derive(Debug, Parameters)]
#[parameters(read_by(StationResource), on(destroy))]
pub struct StationDelete {
    /// `yes` deletes; without it the deletion is only tried, and the
    /// answer says what it would delete.
    pub confirm: Option<Confirm>,
}

/// [`StationDelete::confirm`]'s value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ParamValue)]
pub enum Confirm {
    Yes,
}
}

The resource lists the struct in parameters(..):

#![allow(unused)]
fn main() {
#[derive(Resource)]
#[resource(model = Station, path = "stations", /* … */ parameters(StationDelete))]
pub struct StationResource;
}

And the code reads it, already typed, with ctx.parameters::<P>():

#![allow(unused)]
fn main() {
impl Writes for StationResource {
    async fn deleting(ctx: &Ctx, id: i64) -> Result<Deleted, ApiError> {
        let deleted = /* … */;
        Ok(Deleted {
            body: Some(json!({ "count": deleted.count, "details": deleted.details })),
            simulated: ctx.parameters::<StationDelete>().confirm != Some(Confirm::Yes),
        })
    }
}
}

A client then sends:

DELETE /stations/4?confirm=yes

And a value that is not allowed is refused before anything runs:

DELETE /stations/4?confirm=please
{"confirm": ["Expected one of: yes."]}

The parameter is also in the OpenAPI document of DELETE /stations/{id}, with its description (the doc comment) and its allowed values (yes).

Why a struct, and not request.query_params.get("confirm")? Because the name is then written once. A misspelt name does not compile, a wrong value is a clear 400, and the OpenAPI document cannot forget the parameter. The rest of this chapter explains these guarantees.

The fields and their types

Each field of the struct is one parameter. Its name is the field’s name.

A parameter is never required: a client may always leave it out. So each field says what it is when it is not sent, in one of two ways:

  • The field is an Option<T>. It is None when the parameter is not sent, or is sent empty (?confirm=).
  • The field has a default: #[parameter(default)] uses the type’s Default, and #[parameter(default = …)] gives a value.

A field that is neither does not compile. An Option with a default does not compile either.

Here is a richer example, not taken from the sample:

#![allow(unused)]
fn main() {
// A fragment: what a list of trains could read beside its filters.
#[derive(Parameters)]
#[parameters(read_by(TrainResource, TrainOut), on(list, retrieve))]
pub struct TrainParams {
    /// A superuser's: `true` adds the retired trains to the list,
    /// `only` lists them alone.
    #[parameter(default)]
    pub show_retired: ShowRetired,
    /// `0`: every wagon of a train, not only those in service.
    #[parameter(default = true)]
    pub filter_wagons: bool,
}

#[derive(ParamValue, Default, PartialEq)]
pub enum ShowRetired {
    #[default]
    False,
    True,
    Only,
}
}
#![allow(unused)]
fn main() {
let show = &ctx.parameters::<TrainParams>().show_retired;
if *show == ShowRetired::Only { /* … */ }
}

The value’s type says how the text is read:

  • String: the text as it is sent.
  • bool: true, false, 1 or 0, in any case. Anything else is a 400.
  • integers and floats: parsed as numbers.
  • Vec<T>: a comma-separated list. Empty items are skipped.
  • an enum that derives ParamValue: one of its variants, written in snake case (ShowAll is show_all), or the name you give with #[value(name = "…")]. The OpenAPI document lists the allowed values.

An enum is usually the best type for a parameter with a few allowed values: the code gets a match, and the client gets the list of values.

A parameter that is only present: present

Some old APIs use a parameter without a value: ?flat. What matters is only whether the name is in the query string. #[parameter(present)] on a bool field reads it that way: it is true when the name is there, whatever its value, even empty.

#![allow(unused)]
fn main() {
/// The answer without its nested objects.
#[parameter(present)]
pub flat: bool,
}

In a Django view, this is request.query_params.get("flat") is not None.

Names and descriptions

  • #[parameter(name = "…")] gives the parameter another name than the field’s.
  • #[parameter(alias = "…")] gives it one more name. You can repeat it.
  • The field’s doc comment is the parameter’s description in the OpenAPI document. #[parameter(description = "…")] replaces it.

A value that cannot be read

A value that does not parse is a 400 that names the parameter:

{"show_retired": ["Expected one of: false, true, only."]}

It comes before the first query, together with the filters’ own errors.

Coming from Django: a Django view that reads request.query_params.get(..) usually ignores a wrong value and falls back to its default. rind is stricter: a wrong value is an error the client sees. (A filter’s boolean is the one exception, because django-filter ignores it: see Filters.)

When they are read

on(..) names the operations that read the struct. Before such an operation starts, rind reads the struct from the query string, and a wrong value is a 400. The OpenAPI document lists the parameters on these operations only.

The names are list, retrieve, create, update, destroy, and the names of the resource’s actions. update covers both PUT and PATCH; writing partial_update does not compile. Without on(..), the struct is read by every operation of the resource.

A struct can also be read where on(..) does not say: in another operation, or in a job. It is then read the first time the code asks for it. A value that does not parse at that point gives the field’s default, because it is too late for a 400.

In every case, ctx.parameters::<P>() never fails and never panics. Each struct is read at most once per request.

What does not compile

The point of typing parameters is that a mistake is a compile error, not a parameter silently ignored, nor one the document forgets.

  • A misspelt parameter. ctx.parameters::<StationDelete>().confrim is a field that does not exist.

  • A struct that is read but not listed. read_by(..) names the resources and serializers that read the struct. Each of them must list it in its own parameters(..). Otherwise:

    error[E0277]: `StationResource` reads the parameters `StationDelete` without listing them
    
  • A struct shared by many resources. Such a struct names no reader in read_by. Instead, the functions that read it say whose parameters they are, with a bound: safe_delete::<R: Declares<SafeDelete>>. A resource that deletes through safe_delete without listing SafeDelete does not compile.

  • The same name twice on a resource. A name may appear only once among the resource’s filters, its parameters(..), its behaviours’ parameters, and rind’s own names: page, page_size, ordering, search, fields, omit, include, format, export, no_cache and nocache.

  • A parameter read by its name. ctx.params.get("x") does not compile. The methods that read the query string by name belong to a trait that only rind’s own crates import (rind::__private::RawParams). An application that imports it steps out of the checks on purpose. Nothing in the sample, or in a project made by rind new, does.

Two places are left for you to keep in step by hand:

  • a filterset written by hand (impl FilterSet instead of the derive). It reads through the parser rind gives it, and lists its names in parameters();
  • a hand-written Action’s parameters, which describes what it reads.

Testing a struct

rind::api::parameters::read_from::<P>("confirm=yes") reads a struct from a query string, as a request would. It returns the 400 error when a value does not parse. It is meant for tests.

Filtersets are parameters too

A derived filterset is also a struct of typed parameters, read on list and retrieve. This is useful in two cases.

A filterset of another model. A resource’s mode may filter related rows inside a sub-query, and want the client to choose those filters. The resource lists that filterset in parameters(..), and its query reads it with ctx.parameters::<RelationFilters>() to filter the rows of its EXISTS.

A serializer that reads a filter. A serializer may list its resource’s own filterset to read a filter’s value. In the sample, the stations’ serializer reads the near filter (near=lng,lat,km) to compute each station’s near_km:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Station, /* … */ parameters(StationFilters))]
pub struct StationOut { /* … */ }

async fn near_km(ctx: &Ctx, ids: Vec<i64>) -> Result<HashMap<i64, i64>, ApiError> {
    let point: Vec<f64> = ctx
        .parameters::<StationFilters>()
        /* … */;
    /* … */
}
}

The OpenAPI document lists near once, as a filter.

Behaviours and rind’s own

A behaviour declares what it reads, with type Parameters. Flags reads flags on a list; Images reads image on get_image. Their parameters are listed with the resource’s own, and checked against them for duplicate names.

rind’s safe_delete reads SafeDelete (?doit=really, on destroy).

An ordering expression is given the request, ctx, so it can read typed parameters the same way. For example, #[ordering(by(near = near_order(ctx)))] would sort by a distance, with near_order a function of yours that reads a struct and gives an Option of an ordering.

ctx.ordering() gives the ordering the request asks for, as it was sent (["-name", "id"]). It is for code that sorts by more than the resource’s names, such as the siblings of a tree.

Reference

#[parameters(..)]

KeyMeaning
read_by(A, B)The resources and serializers that read the struct. Each must list it in parameters(..), or the code does not compile.
on(list, retrieve, …)The operations that read it before they start, and whose OpenAPI document lists it. Without it: every operation. update covers partial_update.

#[parameter(..)]

KeyMeaning
name = "…"The parameter’s name, when it is not the field’s.
alias = "…"One more name. Repeatable.
defaultWhen not sent: the type’s Default. Not with Option.
default = exprWhen not sent: this value. Not with Option.
presentOn a bool only, without default: true when the name is in the query string, whatever its value.
description = "…"The OpenAPI description, instead of the doc comment.

Value types

TypeRead asSchema
Stringthe textstring
booltrue, false, 1, 0 (any case)boolean
i16…i64, u16…u64, usizea numberinteger
f32, f64a numbernumber
Vec<T>comma-separated, empty items skippedstring, “Comma-separated.”
an enum deriving ParamValuea variant in snake case, or #[value(name = "…")]string with enum
Option<T>None when not sent or emptyT’s

Another type can be used by implementing rind::api::ParamType (a parse function and a schema function).

Reading them

CodeGives
ctx.parameters::<P>()&P, read once per request; never fails.
ctx.ordering()The ordering asked for, as sent.
rind::api::parameters::read_from::<P>(query)P, or the 400 error: for tests.