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

Resources

A resource serves one model over HTTP. It is what Django REST framework calls a viewset, and most often a ModelViewSet: it answers the list of objects, each object, the writes (create, update, delete) and the actions you add to it.

In Django REST framework, a viewset is a class with attributes: queryset, serializer_class, filterset_class, search_fields, ordering_fields, permission_classes. A rind resource says the same things, but as attributes of a derive on an empty struct. The derive reads them when the code compiles, so a mistake (a field that does not exist, a rule that names an action the resource does not have) is a compile error, not a 500 at the first request.

A first resource

This is the trains resource of the sample application:

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/views.rs
use fleet_models::Train;
use rind::Resource;

use super::filters::TrainFilters;
use super::serializers::{TrainIn, TrainOut};

/// Signed-in users read the trains; the staff writes them.
#[derive(Resource)]
#[resource(
    model = Train,
    path = "trains",
    out = TrainOut,
    filters = TrainFilters,
    input = TrainIn,
    delete,
    options(cache_ttl = 30, cache_by_mode)
)]
#[rule(superuser)]
#[rule(staff)]
#[rule(authenticated, actions(list, retrieve))]
#[search(Train::name(), unaccent)]
#[search(Train::number(), starts_with)]
#[ordering(by(id, number, name), default("number"))]
pub struct TrainResource;
}

The struct has no fields and no methods: everything is in the attributes. The keys of #[resource(..)] are:

  • model: the model the resource serves (DRF’s queryset.model).
  • path: the URL prefix, as given to DRF’s router.register("trains", …).
  • out: the serializer, which says what an object looks like in an answer.
  • input: the input, which says what a client may write.
  • filters: the filterset, which says what the list can be filtered on (django-filter’s FilterSet).
  • delete: the resource accepts DELETE.
  • options(..): settings read by plugins, here the cache.

The other attributes are #[rule], which says who may do what (Permissions), and #[search] and #[ordering], which are DRF’s search_fields, ordering_fields and ordering (Filters).

Coming from Django: there is no Meta.ordering on the model. The resource says its default ordering with #[ordering(.., default("number"))].

What it serves

That one struct serves six routes:

RequestActionAnswer
GET /trainslista page of trains, filtered, searched and ordered
GET /trains/{id}retrieveone train
POST /trainscreatethe new train, with status 201
PUT /trains/{id}updatethe train after the change
PATCH /trains/{id}partial_updatethe train after the change
DELETE /trains/{id}destroyan empty 204

The action names in the second column are the ones DRF uses. Rules name them: #[rule(authenticated, actions(list, retrieve))] lets every signed-in user read the trains, and nothing more.

A list answer is a page. It always has the same three keys:

GET /trains?page_size=2
Authorization: Bearer alice-token
{
  "parameters": {"page": "page", "pagesize": "page_size"},
  "nav": {"size": 2, "page": 1, "next": 2, "prev": null, "count": 3, "pages": 2},
  "results": [
    {"id": 2, "number": "FRET42", "name": "Armor Fret", "kind": "freight", "status": "active", "depot": 2},
    {"id": 3, "number": "TER77", "name": "Cornouaille", "kind": "passenger", "status": "maintenance", "depot": 3}
  ]
}
  • parameters gives the names of the paging parameters, so a client does not have to hard-code them.
  • nav says where the page is: its size, its number, the next and previous page numbers (null when there is none), the number of rows that match the request, and the number of pages.
  • results holds the objects, as the serializer writes them.

Filters, search, ordering, pages explains page and page_size. A retrieve answers one object, without the envelope:

GET /trains/1
{"id": 1, "number": "TGV8601", "name": "Atlantique", "kind": "passenger", "status": "active", "depot": 1}

Which routes exist

A resource only serves what it has the pieces for:

  • Without input, the resource is read-only, like DRF’s ReadOnlyModelViewSet. POST, PUT and PATCH answer 405.
  • Without delete, DELETE answers 405.
  • With actions, the resource also serves the actions written in its #[actions] block, as DRF’s @action methods.

A rule can only name actions the resource has. A typo in actions(list, retreive) does not compile.

Putting the resources together

A resource is not tied to a web framework. The same resource is served by actix-web or by axum.

Resources are grouped by domain: a part of the application with its own models and its own API crate (see Organising an application). The API crate of a domain lists each of its resources once, in a function that depends on neither framework:

#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/lib.rs
pub mod trains;

/// The API of this domain: its resources, mounted by the application.
pub fn api() -> rind::api::Api {
    rind::api::Api::new("fleet").resource::<trains::TrainResource>()
}
}

This list is the equivalent of the DRF router and its register() calls. The application then gathers every domain’s api() in one value, app() (see The command line). When you add a resource with rind add resource, the tool adds it to this chain for you (Starting a project).

To serve the application, you give it an AppState. The state holds the database, the way users sign in, and the tables of the application. Then you mount the routes in the framework you use:

#![allow(unused)]
fn main() {
let app = sample::app();

// axum
let router = app.router(app.state(db));

// actix-web
App::new()
    .app_data(web::Data::new(app.state(db)))
    .configure(|cfg| app.configure(cfg))
}

Most applications do not write this code: rind serve does it (see The command line).

A single resource can still be mounted alone, for a test or a small service: rind::api::axum::router::<R>() for axum, and rind::api::actix::scope::<R>() for actix-web.

Who is asking

Before a resource runs, rind finds out who sent the request. This part belongs to the application: it implements the trait Authenticate. The trait reads the Authorization header and answers an Identity, or no identity for an anonymous request.

An Identity holds what the permission rules look at:

  • id, the user’s id;
  • is_superuser and is_staff, as on Django’s user;
  • groups, the slugs of the user’s groups;
  • data, whatever else the application wants its resources to find there (read it back with identity.data::<T>()).

The sample application keeps a token in a column of its user table (accounts-ops). A real application checks a signed token, for example with rind-auth.

A request without credentials is anonymous. A request with wrong credentials is a 401, even on a resource that anonymous users may read: a client that sends a bad token is told so, rather than silently treated as anonymous. Authentication has the details.

What a resource’s code receives: the context

Everything a resource runs (a hook, an action, a loader of a serializer, a mode’s query) receives a Ctx, the context of the request. It is what DRF gives you through self.request:

  • ctx.db is the database the request works on. During a write, it is the write’s transaction: what you do with it is kept or dropped with the write.
  • ctx.user is the Identity, or None for an anonymous request.
  • ctx.parameters::<P>() gives the request’s typed parameters of type P.
  • ctx.action() gives the action being run ("list", "create", an action’s name). See Permissions.
  • ctx.tables() gives every table of the application (used by deletions).
  • ctx.service::<T>() gives a service a plugin shares, such as the mailer.

When a request fails

A request that fails gets one of these statuses:

StatusWhen
400a body or a query parameter that is not valid; the answer says what is wrong, field by field
401no credentials where they are needed, or wrong credentials
403the user is signed in, and no rule allows the action
404no such object, or an object the user’s mode does not let them see
405the resource does not do that (no input, no delete)
409a deletion refused because other rows still point to the object (Inputs)

The body of an error is JSON. Most errors have a detail key, as in DRF:

{"detail": "You do not have permission to perform this action."}

An invalid body is answered per field, with every error at once:

{"number": ["An object with this value already exists."]}

A constraint that the database refuses (a uniqueness, a check, a foreign key) is a 400 too, not a server error. Most of the time the input catches it first and names the field (Inputs); when it does not, the answer names the constraint:

{"detail": "These values are not allowed (fleet_wagon_capacity_check)."}

Only a fault of the server is a 500. Its cause is logged, and never sent to the client.

Reference

#[resource(..)]

KeyMeaningDRF
model = Mthe model served (required)queryset
path = "…"the URL prefix (required)router.register(prefix, …)
out = Sthe serializer (required)serializer_class, read side
input = Ithe input; without it the resource is read-onlyserializer_class, write side
filters = Fthe filtersetfilterset_class
deleteDELETE is acceptedDestroyModelMixin
hooksyou write impl Writes for … yourself, to check or complete the writesperform_create, perform_update, perform_destroy
mode = Tthe type of the resource’s permission modesget_queryset per user
query = …the base query of a resource without modes: the rows it can see; if it mentions user, an anonymous request sees no rowget_queryset
actionsthe resource serves the actions of its #[actions] block@action
behaviours(..)what it shares with other resources: tracking, flags, markdown, imagesmixins
exports(..)its export formats (xlsx)
parameters(..)the typed parameters it reads, besides its filters’ and its behaviours’
options(..)settings that plugins read: cache_ttl = 60, usage = "skip", a bare name for true
page_size = Nthe default page size, 100 if not givenPAGE_SIZE
max_page_size = Nthe largest page a client may ask for, 50 000 if not givenmax_page_size
ignore_unknown_fieldsan unknown name in fields, omit or include is ignored instead of being a 400

A resource needs at least one #[rule(..)]: without one, nobody could call it, and the derive refuses to compile.

The doc comment of the struct becomes the resource’s description in the OpenAPI document.

The other attributes

AttributeChapter
#[rule(who, actions(..), mode = ..)]Permissions
#[mode(Value, query = .., hide(..))]Permissions
#[search(path, mode)]Filters
#[ordering(by(..), default(..), hidden(..))]Filters

Errors

StatusApiErrorBody
400BadRequest(message){"detail": message}
400Validation(errors){"field": ["message", …], …}
401Unauthorized{"detail": "Authentication credentials were not provided or are invalid."}
403Forbidden{"detail": "You do not have permission to perform this action."}
404NotFound{"detail": "Not found."}
405MethodNotAllowed{"detail": "Method not allowed."}
413{"detail": "Request body too large."}: a body larger than RIND_BODY_LIMIT bytes (32 MiB by default)
anyResponse(status, body)a status and a body of your own
500Database(..), Internal(..){"detail": "Internal server error."}; the cause is logged