Part 3: A first resource
A resource is a model served over HTTP: what Django REST framework
calls a ModelViewSet. It gives a list, a detail, and the writes.
Generating it
rind add resource catalog Book --rule anyone
rind add resource catalog Author --rule anyone
wrote crates/catalog/catalog-api/src/books/mod.rs
wrote crates/catalog/catalog-api/src/books/serializers.rs
wrote crates/catalog/catalog-api/src/books/filters.rs
wrote crates/catalog/catalog-api/src/books/views.rs
edited crates/catalog/catalog-api/src/lib.rs
…
--rule anyone opens the resource to everyone, signed in or not. By
default the tool writes a resource for the staff only: an endpoint that a
generator opens by default is an endpoint that gets deployed open by
mistake. We open both resources now to try them, and we will close them
properly in part 5.
Each resource is a folder with the files a DRF developer expects:
| File | Holds | In DRF |
|---|---|---|
serializers.rs | what a book looks like in an answer, and what can be written | serializers.py |
filters.rs | the query parameters that filter the list | a django-filter FilterSet |
views.rs | the resource: its model, its path, its rules | views.py |
The tool also added the resource to the domain’s api(), in
crates/catalog/catalog-api/src/lib.rs:
#![allow(unused)]
fn main() {
pub fn api() -> rind::api::Api {
rind::api::Api::new("catalog")
.resource::<books::BookResource>()
.resource::<authors::AuthorResource>()
}
}
That is the whole of the routing: there is no urls.py and no router to
register.
The resource
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/views.rs
#[derive(Resource)]
#[resource(
model = Book,
path = "books",
out = BookOut,
filters = BookFilters,
input = BookIn,
delete
)]
#[rule(anyone)]
pub struct BookResource;
}
The struct is empty: everything is in the attributes. model is the
model, path the URL, out the serializer of the answers, input what
can be written, filters the filterset, and delete allows deletions.
#[rule(anyone)] says who may use it.
rind routes lists what it serves:
catalog
/authors GET POST
/authors/{id} DELETE GET PATCH PUT
/books GET POST
/books/{id} DELETE GET PATCH PUT
Two structs: what goes out, what comes in
The generated serializers.rs has two structs. DRF uses one
ModelSerializer for both directions, with read_only and write_only
flags; rind uses two, because what a client reads and what it may write
are rarely the same.
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/serializers.rs
/// A book as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Book)]
pub struct BookOut {
#[field(mandatory)]
pub id: Option<i64>,
pub title: Option<String>,
pub year: Option<i32>,
pub author_id: Option<i64>,
}
/// What can be written on a book.
#[derive(Debug, Input)]
#[input(model = Book)]
pub struct BookIn {
pub title: Option<String>,
pub year: Option<i32>,
pub author_id: Option<i64>,
}
}
Every field of the output is an Option. A client can ask for some
fields only (you will see how below). A field it did not ask for is not
read from the database, and stays None. mandatory means the field is
always sent.
Every field of the input is an Option too, for another reason: a
PATCH sends only some fields. The input knows from the model which
fields are required on a creation.
Let’s improve the generated code a little. DRF sends a foreign key under
the name of the relation ("author": 1), not of the column; and the
input should check that the author exists:
#![allow(unused)]
fn main() {
use catalog_models::{Author, Book};
use rind::{Input, Serializer};
use crate::authors::AuthorOut;
/// A book as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Book)]
pub struct BookOut {
#[field(mandatory)]
pub id: Option<i64>,
pub title: Option<String>,
pub year: Option<i32>,
/// The author's id, under the relation's name.
#[field(name = "author")]
pub author_id: Option<i64>,
/// The whole author, when the client asks for it.
#[nested(key = author_id, on_request)]
pub author_details: Option<AuthorOut>,
}
/// What can be written on a book.
#[derive(Debug, Input)]
#[input(model = Book)]
pub struct BookIn {
#[input(max_length = 200)]
pub title: Option<String>,
pub year: Option<i32>,
#[input(name = "author", fk = Author)]
pub author_id: Option<i64>,
}
}
#[field(name = "author")]sends the field asauthor.#[nested(key = author_id, on_request)]is a nested serializer, like a nestedAuthorSerializerin DRF.on_requestmeans it is sent only when the client asks for it.#[input(name = "author", fk = Author)]reads the field asauthor, and checks that the author exists, with a clear error on the field.#[input(max_length = 200)]checks the length before the database does.
And for the authors, an output with a count of their books:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/authors/serializers.rs
use catalog_models::Author;
use rind::{Input, Serializer};
/// An author as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Author)]
pub struct AuthorOut {
#[field(mandatory)]
pub id: Option<i64>,
pub name: Option<String>,
/// How many books the library has by this author.
#[annotated(expr = Author::books().count(), on_request)]
pub books_count: Option<i64>,
}
/// What can be written on an author.
#[derive(Debug, Input)]
#[input(model = Author)]
pub struct AuthorIn {
#[input(max_length = 100)]
pub name: Option<String>,
}
}
#[annotated(expr = …)] is DRF’s field backed by a queryset
.annotate(...). Author::books() is the reverse relation declared in
part 2, and .count() counts it, in the same SQL query as the list.
Run rind serve, and let’s use the API.
Creating
curl -X POST -H 'Content-Type: application/json' \
-d '{"name": "Frank Herbert"}' localhost:8080/authors
curl -X POST -H 'Content-Type: application/json' \
-d '{"name": "Ursula K. Le Guin"}' localhost:8080/authors
{"id":1,"name":"Frank Herbert"}
{"id":2,"name":"Ursula K. Le Guin"}
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "Dune", "year": 1965, "author": 1}' localhost:8080/books
{"id":1,"title":"Dune","year":1965,"author":1}
Add two more books the same way: The Dispossessed (1974) and A Wizard of Earthsea (1968), both by author 2.
A creation answers 201 Created, with the object as a read would show
it.
Validation errors
An author that does not exist:
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "Children of Dune", "year": 1976, "author": 9}' localhost:8080/books
{"author":["Invalid pk \"9\" - object does not exist."]}
Several problems at once:
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "", "year": "soon"}' localhost:8080/books
{"author":["This field is required."],"title":["This field may not be blank."],"year":["Invalid value."]}
The answer is a 400 Bad Request, with a list of messages per field: the
same shape, and mostly the same messages, as DRF. A client written for a
DRF API reads them as it always has.
Reading
curl localhost:8080/books
{
"parameters": {"page": "page", "pagesize": "page_size"},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 3, "pages": 1},
"results": [
{"id": 3, "title": "A Wizard of Earthsea", "year": 1968, "author": 2},
{"id": 1, "title": "Dune", "year": 1965, "author": 1},
{"id": 2, "title": "The Dispossessed", "year": 1974, "author": 2}
]
}
(The answers in this tutorial are shown indented; the server sends them on one line.)
A list is always paginated. nav says where you are: the page size, the
page number, the next and previous pages, the number of objects and of
pages. results holds the objects. We will come back to it in part 4.
One object:
curl localhost:8080/books/1
{"id":1,"title":"Dune","year":1965,"author":1}
curl localhost:8080/books/99
{"detail":"Not found."}
Choosing the fields
The client chooses the fields with three query parameters: fields
(only these), omit (all but these) and include (the default ones,
plus these):
curl 'localhost:8080/books?fields=title,author_details'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 3, "title": "A Wizard of Earthsea", "author_details": {"id": 2, "name": "Ursula K. Le Guin"}},
{"id": 1, "title": "Dune", "author_details": {"id": 1, "name": "Frank Herbert"}},
{"id": 2, "title": "The Dispossessed", "author_details": {"id": 2, "name": "Ursula K. Le Guin"}}
]
}
id is there because it is mandatory. The authors are read for the
whole page in one query, whatever the number of books: there is no
N+1 problem to think of, and no select_related to remember.
curl 'localhost:8080/authors?include=books_count'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 1, "name": "Frank Herbert", "books_count": 1},
{"id": 2, "name": "Ursula K. Le Guin", "books_count": 2}
]
}
A name that is not a field is an error, not silently ignored:
curl 'localhost:8080/books?fields=price'
{"detail":"Unknown field(s): price."}
Changing and deleting
curl -X PATCH -H 'Content-Type: application/json' \
-d '{"year": 1966}' localhost:8080/books/1
{"id":1,"title":"Dune","year":1966,"author":1}
PATCH changes the fields it sends; PUT expects them all. DELETE /books/{id} answers 204 No Content. Deleting an author who still has
books is refused, because the foreign key says on_delete = restrict.
Coming from Django: where are
get_queryset,perform_createandget_serializer_class? They exist, under other names: the rows a user may see are a permission mode (part 5), and code that runs during a write is a hook (part 5 too). The Resources chapter has the full map.
Next: Part 4: Lists.