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

Inputs: what a client can write

An input says what a client may send to create or change an object, and how each value is checked. It is the write side of Django REST framework’s ModelSerializer: its fields with their validators, validate_<field>(), validate(), create() and update().

The read side is a separate struct, the serializer. That chapter explains why there are two: in short, an answer and a write rarely have the same fields, and a field that is not in the input cannot be written at all. In the sample, a reservation’s status is not in ReservationIn: a client can only change it through the cancel action.

A first input

This is the input of the sample’s stations:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
use chrono::NaiveDate;
use network_models::{Region, Station};
use rind::Input;

/// What can be written on a station.
#[derive(Debug, Input)]
#[input(model = Station, unique(code))]
pub struct StationIn {
    #[input(max_length = 8, validate = upper_case)]
    pub code: Option<String>,
    #[input(max_length = 200)]
    pub name: Option<String>,
    #[input(max_length = 100)]
    pub city: Option<String>,
    #[input(choices("open", "closed"), default = "open")]
    pub status: Option<String>,
    #[input(min = 0, max = 50, default = 0)]
    pub platforms: Option<i32>,
    #[input(default = Vec::<String>::new())]
    pub services: Option<Vec<String>>,
    pub opened: Option<Option<NaiveDate>>,
    #[input(name = "region", fk = Region)]
    pub region_id: Option<i64>,
    #[input(name = "manager", fk = accounts_models::User)]
    pub manager_id: Option<Option<i64>>,
    /// Sent in a form, or in JSON as `{name, type, content}` (base64);
    /// null removes it.
    pub photo: Option<Option<rind::api::files::Upload>>,
    /// `{lng, lat}`; null removes it.
    pub position: Option<Option<rind::db::geo::Point>>,
}

fn upper_case(code: &str) -> Result<(), String> {
    if code.chars().any(char::is_lowercase) {
        return Err("Use upper case.".to_owned());
    }
    Ok(())
}
}

#[input(model = Station)] says which model the input writes. Each field is a column of that model, with the same name unless column = … says another. The resource names the input with input = StationIn (Resources); a resource without an input is read-only.

A creation sends the fields as JSON, and gets the new object back, as a read would show it, with status 201:

POST /stations
Authorization: Bearer staff-token
Content-Type: application/json

{"code": "NTE", "name": "Nantes", "city": "Nantes", "region": 1}
{"id": 101, "code": "NTE", "name": "Nantes", "city": "Nantes", "status": "open",
 "platforms": 0, "services": [], "opened": null, "region": 1, "manager": null,
 "photo": null, "position": null}

status, platforms and services were not sent, so they got their default. The answer is written by the resource’s serializer, and it follows fields= as a read does.

A body that is not right gets a 400 with every error at once, per field, in the words that DRF uses:

POST /stations

{"code": "far-too-long", "name": "  ", "city": "x", "status": "burning",
 "platforms": 99, "services": "wifi", "opened": "yesterday", "region": 404,
 "manager": 404}
{"code": ["Ensure this field has no more than 8 characters.", "Use upper case."],
 "name": ["This field may not be blank."],
 "status": ["\"burning\" is not a valid choice."],
 "platforms": ["Ensure this value is less than or equal to 50."],
 "services": ["Invalid value."],
 "opened": ["Invalid value."],
 "region": ["Invalid pk \"404\" - object does not exist."],
 "manager": ["Invalid pk \"404\" - object does not exist."]}

A client written for a DRF API can show these messages as it did before.

Why every field is an Option

Every field of an input is an Option, and None means “the client did not send this field”. This is how rind tells “not sent” from “sent”: a PATCH changes only the fields that are Some.

A column that can be NULL has two Options: Option<Option<T>>. The outer one says whether the field was sent; the inner one is the value, None when the client sent null. A field with a single Option cannot be set to null: sending null is the error “This field may not be null.”

On a creation, a field is required unless one of these is true:

  • it has a default;
  • it is nullable (Option<Option<T>>);
  • it is marked optional: the column’s default in the database then applies.

A missing required field is “This field is required.”:

POST /stations

{}
{"code": ["This field is required."],
 "name": ["This field is required."],
 "city": ["This field is required."],
 "region": ["This field is required."]}

POST, PUT and PATCH

The three write methods read the same input, in different ways:

  • POST creates an object. A field that is not sent takes its default. A required field that is not sent is an error.
  • PUT replaces the object’s fields. Every required field must be sent, as for a creation. The fields that are not required and not sent keep their value: a default is only for creations.
  • PATCH changes the fields that are sent, and nothing else. No field is required.

All three answer the object as it is after the write (201 for a creation, 200 for the others).

A write must leave the object where the user can still see it. When a user’s mode only shows some rows, a write that would move the object out of those rows is refused with a 403, and nothing is written. DRF has no such check.

Checking a value

Each field can carry checks. They run on the value that was sent, and every failure is reported:

#![allow(unused)]
fn main() {
#[input(max_length = 8, validate = upper_case)]
pub code: Option<String>,
#[input(choices("open", "closed"), default = "open")]
pub status: Option<String>,
#[input(min = 0, max = 50, default = 0)]
pub platforms: Option<i32>,
}
  • max_length = N: a text of at most N characters.
  • min = N and max = N: bounds for a number.
  • choices("a", "b"): the values accepted, as DRF’s ChoiceField.
  • validate = function: a check of your own, as DRF’s validate_<field>(). The function receives the value and gives back Err(message) to refuse it: fn(&T) -> Result<(), String>.

Texts get some care, as in DRF:

  • A text is written without the spaces around it: " Rennes " is written as "Rennes". keep_spaces writes it as it was sent.
  • An empty text (or one made only of spaces) is refused with “This field may not be blank.”. allow_blank accepts it.
  • normalize = function changes the text before it is written, for example normalize = str::to_uppercase for a code. It runs after the spaces are removed, and before the checks.

JSON values are read strictly. "12" is not a number, and "false" is not a boolean: both are “Invalid value.”. A value of the wrong type never reaches the checks.

Checks across fields

A rule that involves several fields goes on the struct, as DRF’s validate():

#![allow(unused)]
fn main() {
// A fragment: the sample's JourneyIn does not have this check.
#[derive(Debug, Input)]
#[input(model = Journey, validate = times_in_order)]
pub struct JourneyIn { … }

fn times_in_order(input: &JourneyIn) -> Result<(), Vec<(&'static str, String)>> {
    match (input.departs_at, input.arrives_at) {
        (Some(departs), Some(arrives)) if arrives <= departs => {
            Err(vec![("arrives_at", "Must be after the departure.".to_owned())])
        }
        _ => Ok(()),
    }
}
}

Each error names the field it belongs to. The function sees only what the body sent: on a PATCH, a field that was not sent is None. A check that needs the object as it is in the database goes in a hook.

Foreign keys, uniqueness and many-to-many fields

Some checks need the database. The input runs them itself, before the write, so that the client gets an answer per field rather than a refused constraint.

A foreign key is checked with fk = Model: the key sent must be the key of a row that exists. Most foreign keys also have a name, so that the client writes the key under the relation’s name, as DRF does and as the serializer sends it:

#![allow(unused)]
fn main() {
#[input(name = "region", fk = Region)]
pub region_id: Option<i64>,
}

A key that does not exist is "Invalid pk \"404\" - object does not exist.". A field without fk is not checked by the input; the database’s foreign key still refuses a wrong key, but the answer is then a general 400 that names the constraint, not the field.

Note: rind add resource writes the input with one field per column, under the column’s name, and without fk. For a foreign key such as author_id, add #[input(name = "author", fk = Author)] yourself.

Uniqueness is checked with unique(..) on the struct:

#![allow(unused)]
fn main() {
#[input(model = Station, unique(code))]
}

No other row may have the same value (or, with several fields, the same values together). The object being changed does not count. The answer is {"code": ["An object with this value already exists."]} for one field, and {"non_field_errors": ["The fields a, b must make a unique set."]} for several. Uniqueness is only checked when every other check passed.

A many-to-many field is a list of ids, with m2m = HOP. HOP is the constant that the model’s #[m2m(..)] makes (LINE_IMAGES):

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
/// The images of its gallery, all at once: the ids of existing images.
#[input(m2m = network_models::LINE_IMAGES)]
pub images: Option<Vec<i64>>,
}

Each id must exist. After the row is written, in the same transaction, the link table’s rows become exactly that set: links that are not in the list are deleted, and missing ones are added. This is DRF’s ManyRelatedField and its set(). A field that is not sent leaves the links as they are.

Forms and files

A body can also be a form (multipart/form-data). Its values are text, so rind reads each one as the field’s type: 12 for a number, true for a boolean. An empty value for a nullable field that is not a text is null.

A field of type Upload is a file. It can be sent in a form, or in JSON as {name, type, content} with the content in base64. The file is stored before the write. folder = "images" stores it in that folder, as images/<sha1>/<name>, as Django’s upload_to does. See Files.

How a write can be checked or completed

Some writes need more than an input: a check that reads other tables, a column the server sets itself, a row to write elsewhere. In DRF, this goes in perform_create(), in serializer.create(), or in the model’s save(). In rind, it goes in hooks.

A resource declared with hooks implements the trait Writes itself. Each hook has a default that does nothing, so you write only the ones you need:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[derive(Resource)]
#[resource(model = Reservation, path = "reservations", /* … */ input = ReservationIn, hooks)]
pub struct ReservationResource;

impl Writes for ReservationResource {
    async fn creating(
        ctx: &Ctx,
        input: &ReservationIn,
        insert: Insert<Reservation>,
    ) -> Result<Insert<Reservation>, ApiError> {
        let user = ctx.user.as_ref().ok_or(ApiError::Unauthorized)?;
        // The room is checked, and kept until the reservation is written:
        // the journey's row is locked.
        booking_ops::check(&ctx.db, request(input)).await.map_err(refused)?;
        Ok(insert
            .value(Reservation::code(), new_code())
            .value(Reservation::booked_by_id(), user.id))
    }
}
}

creating receives the input that was read and checked, and the insert it produced. It can refuse the write by returning an error, or add columns to the insert: here the reservation’s code, and the user who made it.

Every hook runs in the write’s transaction: ctx.db is that transaction. If a hook fails, nothing of the write is kept.

HookWhen it runsWhat it is for
creating(ctx, input, insert)before the insertchecks that need the database; columns a creation sets by itself
updating(ctx, current, input, partial, update)before the updatethe same, with the object as it is now; partial is false for a PUT
saved(ctx, id, input, created)after the insert or the updatewhat a write changes outside the object’s own row
deleting(ctx, id)instead of the deletewhat a deletion takes with it (below)

To refuse a write on one field, return an ApiError::Validation. It is answered as the input’s own errors are:

#![allow(unused)]
fn main() {
fn invalid(field: &str, message: &str) -> ApiError {
    ApiError::Validation([(field.to_owned(), vec![message.to_owned()])].into())
}
}

Coming from Django: there are no signals. What must happen when something else happens is an operation of the domain, a plain function, and each write that needs it calls it by name. You can read a write and see everything it does.

Going further

The order of a write. A creation runs these steps, in one transaction:

  1. The body is read and checked by the input, then the foreign keys and the uniqueness are checked. Any error stops here.
  2. The files sent are stored.
  3. The model’s behaviours, then the resource’s, change the insert.
  4. The creating hook changes the insert, or refuses it.
  5. The row is inserted, and the model’s own hooks run on it.
  6. The many-to-many links are written.
  7. The saved hook runs.
  8. The object is read back through the user’s mode, and answered.

An update runs the same steps with updating. An update that sets nothing (a PATCH with an empty body) runs no statement, but still runs saved.

The answer’s parameters. Writes::answer_params(params, created) gives the query parameters the written object is answered with. By default, they are the request’s own, so fields= applies to a write’s answer as it does to a read.

Writing an object of another resource. An action that creates or changes an object of another resource, in its own transaction, can run that resource’s whole write with rind::api::resource::insert_from::<R>(ctx, &body) and update_from::<R>(ctx, &current, id, &body, partial): the input, the behaviours and the hooks, without the permission check or the answer.

Deleting

By default, DELETE runs one statement and answers an empty 204. What points to the row is then the database’s business: its ON DELETE rules, which the migrations write from the models (#[fk(.., on_delete = …)], see Models).

A resource can instead follow the models itself, in its deleting hook. This lets it say what a deletion would take with it before doing it, much as Django’s admin shows the objects a deletion would remove:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
/// What a deletion of a station reads; the resource lists it,
/// `#[resource(.., parameters(StationDelete))]`.
#[derive(Debug, Parameters)]
#[parameters(read_by(StationResource), on(destroy))]
pub struct StationDelete {
    /// `yes` deletes; without it the deletion is only tried.
    pub confirm: Option<Confirm>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ParamValue)]
pub enum Confirm {
    Yes,
}

impl Writes for StationResource {
    async fn deleting(ctx: &Ctx, id: i64) -> Result<Deleted, ApiError> {
        let deleted = delete::cascade(&ctx.db, ctx.tables(), Station::TABLE, vec![id])
            .await
            .map_err(write_error)?;
        Ok(Deleted {
            body: Some(json!({ "count": deleted.count, "details": deleted.details })),
            simulated: ctx.parameters::<StationDelete>().confirm != Some(Confirm::Yes),
        })
    }
}
}

Deleted says what the deletion answers. With a body, the answer is a 200 with that body; without one, an empty 204. With simulated, the transaction is rolled back, so nothing is deleted.

Without confirm=yes, the deletion is only tried:

DELETE /stations/4
{"count": 1, "details": [["network_station", 1]]}

Nothing is deleted. DELETE /stations/4?confirm=yes deletes, and answers the same. confirm is a typed parameter: ?confirm=sure is a 400, and the OpenAPI document lists confirm on the deletion.

delete::cascade follows each foreign key’s on_delete, whoever would apply it otherwise: the database (the migrations’ ON DELETE), or nobody (a key marked in_code, or a database that Django made, whose keys do nothing). Where the database would have done it, nothing is left for it to do; either way, the walk is what counts the rows.

A key that neither cascades nor empties (restrict, or no rule) refuses the deletion while a row that is not deleted with the rest points to the object. The error is Referenced, and the answer is a 409 that names the key:

{"detail": "This object cannot be deleted: booking_reservation.wagon_id still refers to it.",
 "referenced_by": "booking_reservation.wagon_id"}

Django raises ProtectedError in this case, which is a 500 unless something catches it.

Tried first: safe_delete

The same thing is ready made, in the form that a real Django application used: the deletion is only tried unless the request says ?doit=really, and the answer is {"count", "details"} by table name. The function reads the parameters SafeDelete, which the resource lists: without them, safe_delete does not compile for that resource.

#![allow(unused)]
fn main() {
#[resource(model = Line, path = "lines", delete, hooks,
           parameters(rind::api::delete::SafeDelete))]
pub struct LineResource;

impl Writes for LineResource {
    async fn deleting(ctx: &Ctx, id: i64) -> Result<Deleted, ApiError> {
        rind::api::delete::safe_delete::<LineResource>(ctx, id).await
    }
}
}

A row that refuses (restrict, no_action) makes it a 409 that names it, whether the deletion is tried or confirmed.

Tables no model describes

When you port part of a database to rind, you model some tables. The others still belong to the old application, and some of them point to the modelled ones. A deletion must know them, or the database refuses it. The application gives them as foreign tables: a name, a primary key, the foreign keys, and nothing else.

#![allow(unused)]
fn main() {
static FOREIGN: &[Table] = &[Table::foreign("sales_billitem", "id", &[
    ColumnDef::key("bill_id", "sales_bill", OnDelete::Cascade),
    ColumnDef::key("producer_id", "structures_producer", OnDelete::SetNull),
])];

rind::Application::new("The shop", env!("CARGO_PKG_VERSION"))
    .foreign_tables(FOREIGN.to_vec())
}

A deletion walks them as it walks the models’ tables: into them, on from them (sales_billitem to its own dependants), emptying their keys, or refused by them. They are never migrated, never read otherwise, and not in the OpenAPI document. dbcheck checks that each one exists, with its key columns and their foreign keys. rind inspect writes them, from the database and from the old application’s rules (Inspect).

Reference

Keys of a field

KeyMeaning
name = "…"the key in the body, when it is not the field’s name
column = …the model’s column, when it is not the field’s name
description = "…"the OpenAPI description, instead of the doc comment (or the model column’s); "" gives none
max_length = Na text of at most N characters
min = N, max = Nbounds for a number
choices("a", "b")the values accepted
default = …the value of a creation that does not send the field; for a nullable field too, a value and not null
optionalcan be left out of a creation: the column’s database default applies
allow_blankan empty text is accepted
keep_spacesa text is written as sent (by default, without the spaces around it, as DRF does)
normalize = functionthe text written is the function’s result (str::to_uppercase), after the trim and before the checks; text fields only
validate = functiona check of your own, fn(&T) -> Result<(), String>
fk = Modelthe key must be the key of an existing row (for a list, each key)
m2m = HOPan Option<Vec<i64>>: the ids of a many-to-many relation’s targets; each must exist; the links become that set after the row is written, in its transaction; not sent, they are left as they are; no fk, no default
folder = "…"an Upload stored in that folder, folder/<sha1>/<name>, as Django’s upload_to (Files)
skipread and checked, but not a column: for a hook to use

Keys of the struct

KeyMeaning
model = Mthe model written (required)
unique(a, b)no other row has these values together; can be given several times
validate = functiona check across fields, fn(&Self) -> Result<(), Vec<(&'static str, String)>>

Error messages

MessageWhen
This field is required.a required field is missing from a POST or a PUT
This field may not be null.null sent for a field that is not nullable
This field may not be blank.an empty text, without allow_blank
Invalid value.a value of the wrong type
Ensure this field has no more than N characters.max_length
Ensure this value is greater than or equal to N.min
Ensure this value is less than or equal to N.max
"x" is not a valid choice.choices
Invalid pk "x" - object does not exist.fk, m2m
An object with this value already exists.unique with one field
The fields a, b must make a unique set.unique with several fields, under non_field_errors

A body that is not a JSON object is a 400, {"detail": "Expected a JSON object."}, and a body that is not JSON at all is {"detail": "Invalid JSON: …"}. A field in the body that the input does not have is ignored, as in DRF.