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

OpenAPI

An OpenAPI document describes an API: its routes, their parameters, the JSON they take and send, and who may call them. Clients, code generators and tools such as Swagger UI read it.

In a Django project, the document usually comes from drf-spectacular, which reads the views and serializers and guesses what it cannot read. The guesses are often wrong, and the project corrects them with @extend_schema. In rind, the document is written by the same derives that serve the API. It cannot say something else than what the API does, and there is nothing to guess.

Getting the document

The document belongs to the application, the value returned by app(). Every resource that an api crate’s api() mounts is in it:

#![allow(unused)]
fn main() {
let document: serde_json::Value = sample::app().openapi();
}

The command line writes it to a file:

rind openapi --out openapi.json          # or: cargo run -p sample -- openapi

rind does not serve the document on a route by itself. To serve it, add one route of your own that answers app().openapi(), as described in Routes that are not resources.

The sample freezes its document in a snapshot test (sample/tests/openapi.rs). A change of the API then shows up as a change of the snapshot, which someone reviews.

What the document says

Each part of a resource adds its part of the document:

FromThe document gets
the resourceits routes, as they are served: no POST without an input, no DELETE unless the resource has delete, one route per action
its ruleswho may call each operation (x-allowed), and whether it needs credentials (security)
the serializerthe schema of the output, each field with its type; nested outputs by reference
the inputthe schema of the body: required fields, maxLength, minimum, maximum, enum, nullable
the filtersetone parameter per filter, and one per alias
search, ordering, pagessearch, ordering with the names it accepts, page, page_size, fields, omit, include
an action’s #[query] argumentsthe parameters of the action’s route
typed parametersthe resource’s, its behaviours’ and its serializers’, on the operations their on(..) names
the export formatsformat and export on every read, and the formats’ media types

An operation that no rule allows is left out of the document, since nobody can call it.

Each field of an output has a type that describes itself, through the JsonSchema trait. rind implements it for the usual types, and the Serializer derive implements it for every output. A type of your own used in an output must implement it too: one function that returns its schema. Without it, the code does not compile, so the document is never silently vague about a field.

Routes that are not resources (a webhook, a health check) are not in the document by themselves. .describe(..) adds them: see Routes that are not resources.

Descriptions come from the doc comments

You do not write descriptions twice. Every doc comment (///) goes where the document has a place for it:

A doc comment onDescribes
a resource structits tag (in tags, at the top of the document)
an output structits schema
an output’s fieldits property (before the “Always sent.” that the field selection adds)
an input’s fieldthe body’s property
a filter’s fieldits query parameter, and its aliases
a typed parameter’s fieldits query parameter
an #[action] functionits operation: the first line is the summary, the whole comment the description
a model’s fieldan output or input field of that column that has no comment of its own
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// Stations offering every one of these services.
#[filter(path = Station::services(), lookup = contains)]
pub services: Option<Vec<String>>,
}

This filter’s parameter in the document says “Stations offering every one of these services.”, followed by “Comma-separated.” because its type is a list.

A field is best documented once, on the model. Every serializer and every input of that field then says the same. A comment on the serializer’s or the input’s field replaces the model’s.

The lines are kept as they are written, because descriptions in OpenAPI are CommonMark. Rustdoc’s links become their text ([`Writes`] becomes `Writes`), since a client does not have the crate. A link to a web address is kept.

Sometimes a doc comment is written for the readers of the code, not for the users of the API. Then #[field(description = "…")], #[input(description = "…")], #[filter(description = "…")] and #[parameter(description = "…")] replace it, and description = "" gives no description at all.

The actions that rind’s behaviours add (add_flag, add_image…) carry their own descriptions.

When you start from an existing database, rind inspect writes each column’s database comment (COMMENT ON COLUMN, Django’s db_comment) as the model field’s doc comment, so it reaches the document too.

What is not described yet

  • The body and the answer of an action: the document says that an action takes a JSON body, and answers JSON, without their schema.
  • The fields that a mode hides.

Reference

Where to get it

Code or commandGives
app().openapi()The whole document, as a serde_json::Value.
app().document()The same before it is written, to add to it.
rind openapi [--out FILE]The document as a file, or on standard output.
`.describe(document

Extensions and conventions

In the documentMeaning
x-allowedOn each operation: who may call it (anyone, authenticated, staff, superuser, group(..)).
security: [{"bearer": []}]On an operation no anyone rule allows: it needs credentials.
operationId<path>_<operation>: stations_list, stations_count; stations_count_object for an object action that shares its name with a list action.
tagsOne per resource, its path, described by the resource’s doc comment.