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

Actions

A resource answers six standard operations: list, retrieve, create, update, partial_update and destroy. Real APIs need more: “cancel this reservation”, “delay this journey”, “how many stations are there?”. These are actions: routes of your own, mounted on the resource.

In Django REST framework, they are the methods of a ViewSet decorated with @action. An action with detail=True works on one object (/journeys/{id}/delay); one with detail=False works on the list (/stations/count). rind has the same two kinds, and says which one an action is from its arguments.

A first example

The sample’s journeys have two actions: rooms, which reads, and delay, which writes.

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/views.rs
use rind::api::{ApiError, Ctx, QueryParams, resource};
use rind::{Resource, actions};

/// The body of `delay`.
#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Delay {
    pub minutes: i64,
}

#[derive(Resource)]
#[resource(model = Journey, path = "journeys", /* … */ actions)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, rooms))]
pub struct JourneyResource;

#[actions]
impl JourneyResource {
    /// What each wagon of the journey has left.
    #[action(GET)]
    pub async fn rooms(
        ctx: &Ctx,
        journey: Journey,
        #[query] kind: Option<String>,
        #[query(default = false)] free_only: bool,
    ) -> Result<Vec<Room>, ApiError> {
        let rooms = booking_ops::rooms(&ctx.db, &journey).await?;
        Ok(rooms
            .into_iter()
            .filter(|room| kind.as_ref().is_none_or(|kind| *kind == room.kind))
            .filter(|room| !free_only || room.free > 0)
            .collect())
    }

    /// Moves a journey that has not left by a number of minutes.
    #[action(POST)]
    pub async fn delay(
        ctx: &Ctx,
        journey: Journey,
        #[body] delay: Delay,
    ) -> Result<JourneyOut, ApiError> {
        …
        resource::serialize_one::<JourneyResource>(ctx, (), moved, &QueryParams::default()).await
    }
}
}

Three things make this work:

  1. actions in #[resource(..)] tells the resource that it has actions.
  2. #[actions] on an impl block of the resource struct collects the functions marked #[action(..)].
  3. Each action is an async fn with the HTTP method in its attribute. Its name is the function’s name, and it is also the last part of its URL.

Both actions take a journey: Journey, so they work on one object:

GET /journeys/1/rooms?kind=sleeper
[{"wagon": 3, "position": 3, "kind": "sleeper", "capacity": 2, "taken": 1, "free": 1}]
POST /journeys/1/delay
{"minutes": 15}

The answer of delay is the journey as it is afterwards, exactly as GET /journeys/1 would send it.

Choosing the method

An action is GET, POST or PATCH.

Use GET for an action that changes nothing. Such an action may be answered by a replica of the database, and it may be kept by the cache. Use POST or PATCH for an action that writes.

What an action receives

An action asks for what it needs through its arguments. rind recognises most of them by their name, and two by an attribute:

ArgumentWhat it is
ctx: &CtxThe request’s context: the database, the user, the typed parameters.
mode: ReservationModeThe user’s mode, for a resource that has modes.
params: &QueryParamsThe whole query string, to hand to list_query or serialize_one.
#[query] name: TOne parameter of the query string, read as T. Required.
#[query] name: Option<T>The same, optional.
#[query(default = …)] name: TThe same, optional, with a default.
#[body] name: TThe JSON body, read as any Deserialize type. Option<T> when the body may be absent.
any other argument (journey: Journey)The object. Its presence makes the action a detail action.

The object

When an action has an argument that is none of the above, rind takes it as the object: the action is then mounted under an id, /journeys/{id}/rooms. The object is read in the user’s mode, through the same query as a retrieve. A user who cannot see the journey gets a 404, and the action does not run.

An action without such an argument is a list action, mounted on the resource itself: /stations/count. An action has at most one object.

Query parameters

A #[query] argument is read from the query string under its own name (a leading _ is dropped). #[query(name = "…")] reads another name.

A missing required parameter, or a value that is not of its type, is a 400 before the action runs. Every wrong parameter is reported in the same answer:

GET /journeys/1/rooms?free_only=perhaps
{"free_only": ["Invalid value."]}

An action can also read typed parameters: a struct whose on(..) names the action is read before the action runs, like for a standard operation.

The body

A #[body] argument is the JSON body, read into its type with serde. A body that does not fit the type is a 400 (Invalid body: …). With #[serde(deny_unknown_fields)], as on Delay, an unknown key is refused too.

The #[query] and #[body] arguments are part of the OpenAPI document.

What it answers

An action returns Result<T, ApiError>, where T is anything that serializes to JSON: a number, a Vec, a struct of yours, an output.

To answer an object as a read of the resource would, in the user’s mode, use serialize_one:

#![allow(unused)]
fn main() {
resource::serialize_one::<JourneyResource>(ctx, (), moved, &QueryParams::default()).await
}

Its arguments are the context, the mode (() for a resource without modes), the model’s row, and the query string that chooses the fields. QueryParams::default() gives the default fields; passing the action’s params lets the client choose them with ?fields=….

The status

An action answers 200. An action that creates something says so with status:

#![allow(unused)]
fn main() {
#[action(POST, status = 201)]
}

The status must be a 2xx, and not 204, since an action always answers a body. The Images behaviour’s add_image and the Logo behaviour’s set_logo answer 201, as a real Django application’s did.

Who may run it

An action is allowed like any other operation: by its name in the rules. In the example above, rooms is open to everyone, because the anyone rule names it. delay is named by no rule that lists actions, so only the users whose rule allows everything (here, the superusers and the staff) may run it.

A rule that names an action that does not exist does not compile.

An action over the list

Some actions answer about the rows the list would show: a map of them, their counts, a summary. Such an action should follow the same filters, search and ordering as the list, so that ?status=closed means the same thing on both.

rind::api::resource::list_query::<R>(ctx, mode, params) gives that query. It is the mode’s query, with the filters, the behaviours’ filters, the search, and the ordering the request asks for, but without the page. A filter that cannot be read is a 400, as on the list.

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[action(GET, cached)]
pub async fn geojson(ctx: &Ctx, params: &QueryParams) -> Result<FeatureCollection, ApiError> {
    let query = rind::api::resource::list_query::<StationResource>(ctx, (), params)?;
    let select = query
        .select((Station::id(), Station::name(), Station::status(), Station::position()))
        .into_select();
    let rows: Vec<(i64, String, String, Option<Point>)> = ctx.db.rows(&select).await?;
    Ok(FeatureCollection::new(
        rows.into_iter()
            .map(|(id, name, status, position)| {
                Feature::new(id, position).with("name", name).with("status", status)
            })
            .collect(),
    ))
}
}
GET /stations/geojson?status=closed

This maps the closed stations: every one of them, in the list’s order.

Kept by the cache

By default, the cache does not keep the answers of an action, and ETags does not tag them. A GET action whose answer can be kept says so with cached:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
/// How many stations there are.
#[action(GET, cached)]
pub async fn count(ctx: &Ctx) -> Result<i64, ApiError> {
    Ok(ctx.db.count(&Query::<Station>::new()).await?)
}
}

A cached action is kept as a list is kept: per user (or per rule), made stale by any write to the resource’s tables, and answered with a 304 to a client that already has it.

Say cached only of an action that reads nothing but the database, and only through those tables. The sample’s clock action, which sends the server’s time, is not cached: the cache cannot see the clock change. cached on a POST or a PATCH does not compile. The Flags behaviour’s get_flags is cached.

A list action and an object action with the same name

A list action and an object action may share a name. In the sample, /stations/count counts every station, and /stations/{id}/count counts the stations of that station’s city. They are two functions; the second one takes its URL name from name:

#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[action(GET, cached)]
pub async fn count(ctx: &Ctx) -> Result<i64, ApiError> { … }

/// How many stations its city has, itself included.
#[action(GET, cached, name = "count")]
pub async fn city_count(ctx: &Ctx, station: Station) -> Result<i64, ApiError> { … }
}

Whether the URL has an id says which function runs. A rule that names count allows both, and both read the typed parameters declared on(count). In the OpenAPI document, the list action’s operation id is stations_count, and the object action’s is stations_count_object.

A real Django application had such a pair: POST /producers/action (create a producer, look up a company number) and POST /producers/{id}/action.

Where the work goes

An action is HTTP: it reads a request and writes an answer. The work it does belongs to the domain, in an ops crate, as a function that knows nothing about HTTP. That function can then be called from anywhere (a job, a command, a test) and tested alone:

#![allow(unused)]
fn main() {
// sample/crates/booking/booking-ops/src/lib.rs
pub async fn cancel(db: &Db, reservation: i64) -> Result<Reservation, Refused> { … }

// sample/crates/booking/booking-api/src/reservations/views.rs
#[action(POST)]
pub async fn cancel(
    ctx: &Ctx,
    mode: ReservationMode,
    reservation: Reservation,
) -> Result<ReservationOut, ApiError> {
    let cancelled = booking_ops::cancel(&ctx.db, reservation.id)
        .await
        .map_err(refused)?;
    let params = QueryParams::default();
    resource::serialize_one::<ReservationResource>(ctx, mode, cancelled, &params).await
}
}

refused is the API crate’s function that turns the domain’s refusal into an ApiError. See Organising an application.

Coming from Django: a DRF @action often holds the business logic itself. rind does not stop you, but the sample keeps actions thin, the way a Django project would move logic into a services.py.

Reference

#[action(..)]

KeyMeaning
GET, POST or PATCHThe HTTP method. Required.
name = "…"The action’s name (its URL, its rules), when it is not the function’s.
cachedOn a GET only: the cache keeps its answers and ETags tags them.
status = NThe status of its answer: a 2xx other than 204. 200 by default.

Arguments

ArgumentMeaning
ctx&Ctx, the request.
modeThe resource’s mode.
params&QueryParams, the query string.
body (without #[body])The raw JSON body, serde_json::Value; Null without a body.
#[query], #[query(name = "…")], #[query(default = …)]One query parameter, typed. Not Option with default.
#[body]The JSON body, typed.
one other argumentThe object: a detail action, /<path>/{id}/<name>.

A name with a leading _ (_ctx) means the same as without it. An action has no self, and is always an async fn.

Routes

ActionRouteOperation id
with an object/<path>/{id}/<name><path>_<name>, or <path>_<name>_object when a list action has the same name
without/<path>/<name><path>_<name>