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’squeryset.model).path: the URL prefix, as given to DRF’srouter.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’sFilterSet).delete: the resource acceptsDELETE.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.orderingon the model. The resource says its default ordering with#[ordering(.., default("number"))].
What it serves
That one struct serves six routes:
| Request | Action | Answer |
|---|---|---|
GET /trains | list | a page of trains, filtered, searched and ordered |
GET /trains/{id} | retrieve | one train |
POST /trains | create | the new train, with status 201 |
PUT /trains/{id} | update | the train after the change |
PATCH /trains/{id} | partial_update | the train after the change |
DELETE /trains/{id} | destroy | an 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}
]
}
parametersgives the names of the paging parameters, so a client does not have to hard-code them.navsays where the page is: its size, its number, the next and previous page numbers (nullwhen there is none), the number of rows that match the request, and the number of pages.resultsholds 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’sReadOnlyModelViewSet.POST,PUTandPATCHanswer 405. - Without
delete,DELETEanswers 405. - With
actions, the resource also serves the actions written in its#[actions]block, as DRF’s@actionmethods.
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_superuserandis_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 withidentity.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.dbis 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.useris theIdentity, orNonefor an anonymous request.ctx.parameters::<P>()gives the request’s typed parameters of typeP.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:
| Status | When |
|---|---|
| 400 | a body or a query parameter that is not valid; the answer says what is wrong, field by field |
| 401 | no credentials where they are needed, or wrong credentials |
| 403 | the user is signed in, and no rule allows the action |
| 404 | no such object, or an object the user’s mode does not let them see |
| 405 | the resource does not do that (no input, no delete) |
| 409 | a 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(..)]
| Key | Meaning | DRF |
|---|---|---|
model = M | the model served (required) | queryset |
path = "…" | the URL prefix (required) | router.register(prefix, …) |
out = S | the serializer (required) | serializer_class, read side |
input = I | the input; without it the resource is read-only | serializer_class, write side |
filters = F | the filterset | filterset_class |
delete | DELETE is accepted | DestroyModelMixin |
hooks | you write impl Writes for … yourself, to check or complete the writes | perform_create, perform_update, perform_destroy |
mode = T | the type of the resource’s permission modes | get_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 row | get_queryset |
actions | the resource serves the actions of its #[actions] block | @action |
behaviours(..) | what it shares with other resources: tracking, flags, markdown, images | mixins |
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 = N | the default page size, 100 if not given | PAGE_SIZE |
max_page_size = N | the largest page a client may ask for, 50 000 if not given | max_page_size |
ignore_unknown_fields | an 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
| Attribute | Chapter |
|---|---|
#[rule(who, actions(..), mode = ..)] | Permissions |
#[mode(Value, query = .., hide(..))] | Permissions |
#[search(path, mode)] | Filters |
#[ordering(by(..), default(..), hidden(..))] | Filters |
Errors
| Status | ApiError | Body |
|---|---|---|
| 400 | BadRequest(message) | {"detail": message} |
| 400 | Validation(errors) | {"field": ["message", …], …} |
| 401 | Unauthorized | {"detail": "Authentication credentials were not provided or are invalid."} |
| 403 | Forbidden | {"detail": "You do not have permission to perform this action."} |
| 404 | NotFound | {"detail": "Not found."} |
| 405 | MethodNotAllowed | {"detail": "Method not allowed."} |
| 413 | {"detail": "Request body too large."}: a body larger than RIND_BODY_LIMIT bytes (32 MiB by default) | |
| any | Response(status, body) | a status and a body of your own |
| 500 | Database(..), Internal(..) | {"detail": "Internal server error."}; the cause is logged |